SlideShare a Scribd company logo
Copyright 2015 Kirk Pepperdine. All rights reserved
Ripping Apart Java 8
Parallel Streams
Kirk Pepperdine
Copyright 2015 Kirk Pepperdine. All rights reserved
About Me
Specialize in performance tuning

speak frequently about performance

author of performance tuning workshop

Co-founder jClarity

performance diagnositic tooling

Java Champion (since 2006)
Copyright 2015 Kirk Pepperdine. All rights reserved
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Syntaxtic sugar for a specific type of inner class
(parameters) -> body;

() -> 42;

(x,y) -> x * y;
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match = new Function<String,Matcher>() {

@Override

public Matcher apply(String logEntry) {

return applicationTimePattern.matcher(logEntry);

}

};


String example = "2.869: Application time: 1.0001540 seconds";

Matcher matcher = match.apply(example);
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match =
logEntry -> applicationTimePattern.matcher(logEntry);


String example = "2.869: Application time: 1.0001540 seconds";

Matcher matcher = match.apply(example);
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match =
logEntry -> applicationTimePattern.matcher(logEntry);
Predicate<Matcher> matches = new Predicate<Matcher>() {

@Override

public boolean test(Matcher matcher) {

return matcher.find();

}

};


String example = "2.869: Application time: 1.0001540 seconds";
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match =
logEntry -> applicationTimePattern.matcher(logEntry);
Predicate<Matcher> matches = matcher -> matcher.find();


String example = "2.869: Application time: 1.0001540 seconds”;
Boolean b = matches.test(match.apply(example));
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match =
logEntry -> applicationTimePattern.matcher(logEntry);
Predicate<Matcher> matches = matcher -> matcher.find();
Function<Matcher,String> extract = matcher -> {

if ( matches.test( matcher))

return matcher.group(2);

else return "";

};


String example = "2.869: Application time: 1.0001540 seconds”;
String value = extract.apply(match.apply(example));
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
Pattern applicationTimePattern = Pattern.
compile("(d+.d+): Application time: (d+.d+)");

Function<String,Matcher> match =
logEntry -> applicationTimePattern.matcher(logEntry);
Predicate<Matcher> matches = matcher -> matcher.find();
Function<Matcher,String> extract = matcher -> {

if ( matches.test( matcher))

return matcher.group(2);

else return "";

};


Consumer<Matcher> toDouble = matcher -> {

if ( matches.test(matcher))

pauseTimes.add(Double.parseDouble(extract.apply(matcher)));

};



Matcher matcher = match.apply(example);

toDouble.accept(matcher);
Copyright 2015 Kirk Pepperdine. All rights reserved
Lazy Execution
for ( int i = 0; i < 5000; i++) {

LOGGER.fine (() -> "Trace value: " + getValue());

}
for ( int i = 0; i < 5000; i++) {

LOGGER.fine ("Trace value: " + getValue());

}
3200ms
0ms
Copyright 2015 Kirk Pepperdine. All rights reserved
Java 8 Lambda expressions
public void processStrings(
List<String> logEntries,
Function<String,Matcher> mapper,
Consumer collector)
{


logEntries.forEach(
entry -> collector.accept( mapper.apply(entry)));
main.processStrings(logEntries, match, toDouble);
main.processStrings(logEntries, anotherMatch, toKBytes);
Copyright 2015 Kirk Pepperdine. All rights reserved
Language changes in Java 8
Method references
String::length

aString::length

ClassName::new
(aString) -> aString::length;
Copyright 2015 Kirk Pepperdine. All rights reserved
Stream
Abstraction that allows you to apply a set of
functions over the elements in a collection

functions are combined to form a stream pipeline

sequential or parallel

operations divided into intermediate and terminal
operations
Copyright 2015 Kirk Pepperdine. All rights reserved
Stream
Defined in interface Collection::stream()

many classes implement stream()

Arrays.stream(Object[])

Stream.of(Object[]), .iterate(Object,UnaryOperator)

File.lines(), BufferedReader.lines(), Random.ints(),
JarFile.stream()
Copyright 2015 Kirk Pepperdine. All rights reserved
Old School Code
public void imperative() throws IOException {

Population pop = new Population();

String logRecord;

double value = 0.0d;

BufferedReader reader = new BufferedReader(new FileReader(gcLogFileName));

while ( ( logRecord = reader.readLine()) != null) {

Matcher matcher = applicationStoppedTimePattern.matcher(logRecord);

if ( matcher.find()) {

pop.add(Double.parseDouble( matcher.group(2)));

}

}

System.out.println(pop.toString());

}
Copyright 2015 Kirk Pepperdine. All rights reserved
gcLogEntries.stream()



.map(applicationStoppedTimePattern::matcher)



.filter(Matcher::find)



.map(matcher -> matcher.group(2))



.mapToDouble(Double::parseDouble)



.summaryStatistics();
data source
start streaming
map to Matcher
filter out

uninteresting bits
map to Double
extract group
aggregate results
Copyright 2015 Kirk Pepperdine. All rights reserved
Copyright 2015 Kirk Pepperdine. All rights reserved
Parallel Streams
If collection supports Spliterator operations can
be performed in parallel

Spliterator is like an internal iterator

split source into several spliterator

traverse source

Many of the same rules as Iterator

however may work (non-deterministically) with I/O
Copyright 2015 Kirk Pepperdine. All rights reserved
gcLogEntries.stream().parallel().



.map(applicationStoppedTimePattern::matcher)



.filter(Matcher::find)



.map(matcher -> matcher.group(2))



.mapToDouble(Double::parseDouble)



.summaryStatistics();
parallelize stream
Copyright 2015 Kirk Pepperdine. All rights reserved
Copyright 2015 Kirk Pepperdine. All rights reserved
The first time we tried,

the imperative single threaded code
Copyright 2015 Kirk Pepperdine. All rights reserved
ran faster

(????)
Copyright 2015 Kirk Pepperdine. All rights reserved
Flat profile of 8.70 secs (638 total ticks): ForkJoinPool.commonPool-worker-3

Compiled + native Method 

60.8% 118 + 0 java.util.concurrent.ForkJoinTask.doExec
Raw Profiler Output
Copyright 2015 Kirk Pepperdine. All rights reserved
Flat profile of 8.70 secs (638 total ticks): ForkJoinPool.commonPool-worker-3

Compiled + native Method 

60.8% 118 + 0 java.util.concurrent.ForkJoinTask.doExec
Raw Profiler Output
Learned 2 things very quickly

Parallel streams use Fork-Join

Fork-Join comes with some significant over-
head
Copyright 2015 Kirk Pepperdine. All rights reserved
Predicted that applcations using parallel
streams would
For other reasons….
run very very slowly
Copyright 2015 Kirk Pepperdine. All rights reserved
Then, witnessing it!
Copyright 2015 Kirk Pepperdine. All rights reserved
When to use Streams
Tragedy of the commons

Handoff costs

CNPQ performance model

Fork-Join
Copyright 2015 Kirk Pepperdine. All rights reserved
Tragidy of the Commons
Copyright 2015 Kirk Pepperdine. All rights reserved
You have a finite amount of hardware

it might be in your best interest to grab it all

if everyone behaves the same way….
Be a good neighbour
Copyright 2015 Kirk Pepperdine. All rights reserved
Handoff Costs
It costs about ~80,000 clocks to handoff data
between threads
overhead = 80000*handoff rate/cycles
10%= 80000*handoff rate/2000000000
~2500 handoffs/sec
Copyright 2015 Kirk Pepperdine. All rights reserved
CPNQ Performance Model
C - number of submitters

P - number of CPUs

N - number of elements

Q - cost of the operation
Copyright 2015 Kirk Pepperdine. All rights reserved
C/P/N/Q
Need to amortize setup costs

NQ needs to be large

Q can often only be estimated

N often should be > 10,000 elements

P assumes CPU is the limiting resource
Copyright 2015 Kirk Pepperdine. All rights reserved
Fork-Join
Support for Fork-Join added in Java 7

difficult coding idiom to master

Streams make Fork-Join more reachable

how fork-join works and performs is important to your
latency picture
Copyright 2015 Kirk Pepperdine. All rights reserved
Implementation
Used internally by a parallel stream

break the stream up into chunks and submit each chunk
as a ForkJoinTask

apply filter().map().reduce() to each ForkJoinTask

Calls ForkJoinTask invoke() and join() to retrieve results
Copyright 2015 Kirk Pepperdine. All rights reserved
Common Thread Pool
Fork-Join by default uses a common thread pool

default number of worker threads == number of logical
cores - 1

Always contains at least one thread
Copyright 2015 Kirk Pepperdine. All rights reserved
Little’s Law
Fork-Join uses a work queue

work queue behavior can be modeled using Little’s Law
Number of tasks in the system is the

Arrival rate * average service time
Copyright 2015 Kirk Pepperdine. All rights reserved
Little’s Law Example
System sees 400 TPS. It takes 100ms to process a
request

Number of tasks in system = 0.100 * 400 = 40

On an 8 core machine

implies 39 Fork-Join tasks are sitting in queue
accumulating dead time

40*100 = 4000 ms of which 3900 is dead time

97.5% of service time is in waiting
Copyright 2015 Kirk Pepperdine. All rights reserved
Normal Reaction
if there is sufficient capacity then

make the pool bigger

else

add capacity

or 

tune to reduce strength of the dependency
Copyright 2015 Kirk Pepperdine. All rights reserved
Configuring Common Pool
Size of common ForkJoinPool is 

Runtime.getRuntime().availableProcessors() - 1

Can configure things
-Djava.util.concurrent.ForkJoinPool.common.parallelism=N
-Djava.util.concurrent.ForkJoinPool.common.threadFactory
-Djava.util.concurrent.ForkJoinPool.common.exceptionHandler
Copyright 2015 Kirk Pepperdine. All rights reserved
All Hands on Deck!!!
Everyone is working together to get it done!
Copyright 2015 Kirk Pepperdine. All rights reserved
Resource Dependency
If task is CPU bound, you can’t increase the size
of the thread pool

CPU may not be the limiting factor

throughput is limited by another dependent resource

I/O, shared variable (lock)

Adding threads == increased latency

predicted by Little’s Law
Copyright 2015 Kirk Pepperdine. All rights reserved
ForkJoinPool invoke
ForkJoinPool.invoke(ForkJoinTask) uses the
submitting thread as a worker

If 100 threads all call invoke(), we would have
100+ForkJoinThreads exhausting the limiting resource, e.g.
CPUs, IO, etc.
Copyright 2015 Kirk Pepperdine. All rights reserved
ForkJoinPool submit/get
ForkJoinPool.submit(Callable).get() suspends the
submitting thread

If 100 jobs all call submit(), the work queue can become
very long, thus adding latency
Copyright 2015 Kirk Pepperdine. All rights reserved
Our own ForkJoinPool
When used inside a ForkJoinPool, the
ForkJoinTask.fork() method uses the current pool
ForkJoinPool ourOwnPool = new ForkJoinPool(10);

ourOwnPool.invoke(() -> stream.parallel(). …
Copyright 2015 Kirk Pepperdine. All rights reserved
ForkJoinPool
public void parallel() throws IOException {

ForkJoinPool forkJoinPool = new ForkJoinPool(10);

Stream<String> stream = Files.lines(

new File(gcLogFileName).toPath());

forkJoinPool.submit(() ->

stream.parallel()

.map(applicationStoppedTimePattern::matcher)

.filter(Matcher::find)

.map(matcher -> matcher.group(2))

.mapToDouble(Double::parseDouble)

.summaryStatistics().toString());

}
Copyright 2015 Kirk Pepperdine. All rights reserved
ForkJoinPool Observability
ForkJoinPool comes with no visibility

need to instrument ForkJoinTask.invoke()

gather needed from ForkJoinPool needed to feed into
Little’s Law
Copyright 2015 Kirk Pepperdine. All rights reserved
Instrumenting ForkJoinPool
We can get the statistics needed from
ForkJoinPool needed for Little’s Law

need to instrument ForkJoinTask::invoke()
public final V invoke() {

ForkJoinPool.common.getMonitor().submitTask(this);

int s;

if ((s = doInvoke() & DONE_MASK) != NORMAL) reportException(s);

ForkJoinPool.common.getMonitor().retireTask(this);

return getRawResult();

}
Copyright 2015 Kirk Pepperdine. All rights reserved
In an application where you have many
parallel stream operations all running
concurrently performance will be limited
by the size of the common thread pool
Copyright 2015 Kirk Pepperdine. All rights reserved
Benchmark Alert!!!!!!
Copyright 2015 Kirk Pepperdine. All rights reserved
Performance
Submitt log parsing to our own ForkJoinPool
new ForkJoinPool(16).submit(() -> ……… ).get()

new ForkJoinPool(8).submit(() -> ……… ).get()

new ForkJoinPool(4).submit(() -> ……… ).get()
Copyright 2015 Kirk Pepperdine. All rights reserved
16 worker
threads
8 worker
threads
4 worker
threads
Copyright 2015 Kirk Pepperdine. All rights reserved
0
75000
150000
225000
300000
Stream Parallel Flood Stream Flood Parallel
Copyright 2015 Kirk Pepperdine. All rights reserved
Going parallel might not give you the expected gains
Copyright 2015 Kirk Pepperdine. All rights reserved
You may not know this until you hit production!
Copyright 2015 Kirk Pepperdine. All rights reserved
Monitoring internals of JDK is important to
understanding where bottlenecks are
Copyright 2015 Kirk Pepperdine. All rights reserved
JDK is not all that well instrumented
Copyright 2015 Kirk Pepperdine. All rights reserved
APIs have changed so you need to re-read the
javadocs

even for your old familiar classes
Copyright 2015 Kirk Pepperdine. All rights reserved
Performance Seminar
www.kodewerk.com
Java
Performance
Tuning,
May 26-29, Chania
Greece

More Related Content

What's hot

It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know it
Simon Ritter
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
Sven Ruppert
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trains
Grzegorz Duda
 
It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!
Simon Ritter
 
Let's Get to the Rapids
Let's Get to the RapidsLet's Get to the Rapids
Let's Get to the Rapids
Maurice Naftalin
 
Splat
SplatSplat
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
Haim Yadid
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
Kros Huang
 
Python to scala
Python to scalaPython to scala
Python to scala
kao kuo-tung
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
James Dunkerley
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
José Paumard
 
JVM Language Summit: Object layout workshop
JVM Language Summit: Object layout workshopJVM Language Summit: Object layout workshop
JVM Language Summit: Object layout workshop
Azul Systems, Inc.
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
Shouheng Yi
 
Ibis: Seamless Transition Between Pandas and Apache Spark
Ibis: Seamless Transition Between Pandas and Apache SparkIbis: Seamless Transition Between Pandas and Apache Spark
Ibis: Seamless Transition Between Pandas and Apache Spark
Databricks
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
Quintagroup
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
Simon Ritter
 
Java Performance: Speedup your application with hardware counters
Java Performance: Speedup your application with hardware countersJava Performance: Speedup your application with hardware counters
Java Performance: Speedup your application with hardware counters
Sergey Kuksenko
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
meij200
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Thomas Wuerthinger
 
A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...
Valerio Morfino
 

What's hot (20)

It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know it
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trains
 
It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!
 
Let's Get to the Rapids
Let's Get to the RapidsLet's Get to the Rapids
Let's Get to the Rapids
 
Splat
SplatSplat
Splat
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
 
JVM Language Summit: Object layout workshop
JVM Language Summit: Object layout workshopJVM Language Summit: Object layout workshop
JVM Language Summit: Object layout workshop
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
 
Ibis: Seamless Transition Between Pandas and Apache Spark
Ibis: Seamless Transition Between Pandas and Apache SparkIbis: Seamless Transition Between Pandas and Apache Spark
Ibis: Seamless Transition Between Pandas and Apache Spark
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
 
Java Performance: Speedup your application with hardware counters
Java Performance: Speedup your application with hardware countersJava Performance: Speedup your application with hardware counters
Java Performance: Speedup your application with hardware counters
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
 
A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...
 

Viewers also liked

Tech talks annual 2015 william louth_software memories - simulated machines
Tech talks annual 2015 william louth_software memories - simulated machinesTech talks annual 2015 william louth_software memories - simulated machines
Tech talks annual 2015 william louth_software memories - simulated machines
TechTalks
 
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
TechTalks
 
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
Ed Chi
 
Datadriven organizations and the digital customer journey
Datadriven organizations and the digital customer journeyDatadriven organizations and the digital customer journey
Datadriven organizations and the digital customer journey
Elisabeth Bitsch-Christensen
 
BirchBox the Future Business Model of E-Commerce
BirchBox the Future Business Model of E-CommerceBirchBox the Future Business Model of E-Commerce
BirchBox the Future Business Model of E-Commerce
Yelena Starikova
 
Applied Thermal Engineering
Applied Thermal EngineeringApplied Thermal Engineering
Applied Thermal Engineering
Arvind Bhosale
 
Manufacturing Proecesses
Manufacturing ProecessesManufacturing Proecesses
Manufacturing Proecesses
Arvind Bhosale
 
Mechanical drives & power transmission
Mechanical drives & power transmissionMechanical drives & power transmission
Mechanical drives & power transmission
James Shearer
 
State of Robotics 2015
State of Robotics 2015State of Robotics 2015
State of Robotics 2015
HAX
 

Viewers also liked (9)

Tech talks annual 2015 william louth_software memories - simulated machines
Tech talks annual 2015 william louth_software memories - simulated machinesTech talks annual 2015 william louth_software memories - simulated machines
Tech talks annual 2015 william louth_software memories - simulated machines
 
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
Tech talks annual 2015 izzet mustafayev_performance testing - the way to make...
 
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
Model-based Research in Human-Computer Interaction (HCI): Keynote at Mensch u...
 
Datadriven organizations and the digital customer journey
Datadriven organizations and the digital customer journeyDatadriven organizations and the digital customer journey
Datadriven organizations and the digital customer journey
 
BirchBox the Future Business Model of E-Commerce
BirchBox the Future Business Model of E-CommerceBirchBox the Future Business Model of E-Commerce
BirchBox the Future Business Model of E-Commerce
 
Applied Thermal Engineering
Applied Thermal EngineeringApplied Thermal Engineering
Applied Thermal Engineering
 
Manufacturing Proecesses
Manufacturing ProecessesManufacturing Proecesses
Manufacturing Proecesses
 
Mechanical drives & power transmission
Mechanical drives & power transmissionMechanical drives & power transmission
Mechanical drives & power transmission
 
State of Robotics 2015
State of Robotics 2015State of Robotics 2015
State of Robotics 2015
 

Similar to Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams

Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
Maurice Naftalin
 
Production Time Profiling and Diagnostics on the JVM
Production Time Profiling and Diagnostics on the JVMProduction Time Profiling and Diagnostics on the JVM
Production Time Profiling and Diagnostics on the JVM
Marcus Hirt
 
Cooperative Task Execution for Apache Spark
Cooperative Task Execution for Apache SparkCooperative Task Execution for Apache Spark
Cooperative Task Execution for Apache Spark
Databricks
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
Dmitri Nesteruk
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
Eran Harel
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Tom Diederich
 
Toub parallelism tour_oct2009
Toub parallelism tour_oct2009Toub parallelism tour_oct2009
Toub parallelism tour_oct2009
nkaluva
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based Testing
Sumant Tambe
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.ppt
MalathyN6
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
yinonavraham
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
Michal Gajdos
 
DevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on KubernetesDevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on Kubernetes
Dinakar Guniguntala
 
Open mp
Open mpOpen mp
Open mp
Gopi Saiteja
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The Basics
Simon Ritter
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
AEM HUB
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
Justin Edelson
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
Knoldus Inc.
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
Eyal Vardi
 

Similar to Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams (20)

Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
Production Time Profiling and Diagnostics on the JVM
Production Time Profiling and Diagnostics on the JVMProduction Time Profiling and Diagnostics on the JVM
Production Time Profiling and Diagnostics on the JVM
 
Cooperative Task Execution for Apache Spark
Cooperative Task Execution for Apache SparkCooperative Task Execution for Apache Spark
Cooperative Task Execution for Apache Spark
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)
 
Toub parallelism tour_oct2009
Toub parallelism tour_oct2009Toub parallelism tour_oct2009
Toub parallelism tour_oct2009
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based Testing
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.ppt
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
 
DevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on KubernetesDevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on Kubernetes
 
Open mp
Open mpOpen mp
Open mp
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The Basics
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 

Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams

  • 1. Copyright 2015 Kirk Pepperdine. All rights reserved Ripping Apart Java 8 Parallel Streams Kirk Pepperdine
  • 2. Copyright 2015 Kirk Pepperdine. All rights reserved About Me Specialize in performance tuning speak frequently about performance author of performance tuning workshop Co-founder jClarity performance diagnositic tooling Java Champion (since 2006)
  • 3. Copyright 2015 Kirk Pepperdine. All rights reserved
  • 4. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Syntaxtic sugar for a specific type of inner class (parameters) -> body; () -> 42; (x,y) -> x * y;
  • 5. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = new Function<String,Matcher>() {
 @Override
 public Matcher apply(String logEntry) {
 return applicationTimePattern.matcher(logEntry);
 }
 }; 
 String example = "2.869: Application time: 1.0001540 seconds";
 Matcher matcher = match.apply(example);
  • 6. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = logEntry -> applicationTimePattern.matcher(logEntry); 
 String example = "2.869: Application time: 1.0001540 seconds";
 Matcher matcher = match.apply(example);
  • 7. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = logEntry -> applicationTimePattern.matcher(logEntry); Predicate<Matcher> matches = new Predicate<Matcher>() {
 @Override
 public boolean test(Matcher matcher) {
 return matcher.find();
 }
 }; 
 String example = "2.869: Application time: 1.0001540 seconds";
  • 8. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = logEntry -> applicationTimePattern.matcher(logEntry); Predicate<Matcher> matches = matcher -> matcher.find(); 
 String example = "2.869: Application time: 1.0001540 seconds”; Boolean b = matches.test(match.apply(example));
  • 9. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = logEntry -> applicationTimePattern.matcher(logEntry); Predicate<Matcher> matches = matcher -> matcher.find(); Function<Matcher,String> extract = matcher -> {
 if ( matches.test( matcher))
 return matcher.group(2);
 else return "";
 }; 
 String example = "2.869: Application time: 1.0001540 seconds”; String value = extract.apply(match.apply(example));
  • 10. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions Pattern applicationTimePattern = Pattern. compile("(d+.d+): Application time: (d+.d+)");
 Function<String,Matcher> match = logEntry -> applicationTimePattern.matcher(logEntry); Predicate<Matcher> matches = matcher -> matcher.find(); Function<Matcher,String> extract = matcher -> {
 if ( matches.test( matcher))
 return matcher.group(2);
 else return "";
 }; 
 Consumer<Matcher> toDouble = matcher -> {
 if ( matches.test(matcher))
 pauseTimes.add(Double.parseDouble(extract.apply(matcher)));
 };
 
 Matcher matcher = match.apply(example);
 toDouble.accept(matcher);
  • 11. Copyright 2015 Kirk Pepperdine. All rights reserved Lazy Execution for ( int i = 0; i < 5000; i++) {
 LOGGER.fine (() -> "Trace value: " + getValue());
 } for ( int i = 0; i < 5000; i++) {
 LOGGER.fine ("Trace value: " + getValue());
 } 3200ms 0ms
  • 12. Copyright 2015 Kirk Pepperdine. All rights reserved Java 8 Lambda expressions public void processStrings( List<String> logEntries, Function<String,Matcher> mapper, Consumer collector) { 
 logEntries.forEach( entry -> collector.accept( mapper.apply(entry))); main.processStrings(logEntries, match, toDouble); main.processStrings(logEntries, anotherMatch, toKBytes);
  • 13. Copyright 2015 Kirk Pepperdine. All rights reserved Language changes in Java 8 Method references String::length aString::length ClassName::new (aString) -> aString::length;
  • 14. Copyright 2015 Kirk Pepperdine. All rights reserved Stream Abstraction that allows you to apply a set of functions over the elements in a collection functions are combined to form a stream pipeline sequential or parallel operations divided into intermediate and terminal operations
  • 15. Copyright 2015 Kirk Pepperdine. All rights reserved Stream Defined in interface Collection::stream() many classes implement stream() Arrays.stream(Object[]) Stream.of(Object[]), .iterate(Object,UnaryOperator) File.lines(), BufferedReader.lines(), Random.ints(), JarFile.stream()
  • 16. Copyright 2015 Kirk Pepperdine. All rights reserved Old School Code public void imperative() throws IOException { Population pop = new Population(); String logRecord; double value = 0.0d; BufferedReader reader = new BufferedReader(new FileReader(gcLogFileName)); while ( ( logRecord = reader.readLine()) != null) { Matcher matcher = applicationStoppedTimePattern.matcher(logRecord); if ( matcher.find()) { pop.add(Double.parseDouble( matcher.group(2))); } } System.out.println(pop.toString()); }
  • 17. Copyright 2015 Kirk Pepperdine. All rights reserved gcLogEntries.stream() 
 .map(applicationStoppedTimePattern::matcher) 
 .filter(Matcher::find) 
 .map(matcher -> matcher.group(2)) 
 .mapToDouble(Double::parseDouble) 
 .summaryStatistics(); data source start streaming map to Matcher filter out uninteresting bits map to Double extract group aggregate results
  • 18. Copyright 2015 Kirk Pepperdine. All rights reserved
  • 19. Copyright 2015 Kirk Pepperdine. All rights reserved Parallel Streams If collection supports Spliterator operations can be performed in parallel Spliterator is like an internal iterator split source into several spliterator traverse source Many of the same rules as Iterator however may work (non-deterministically) with I/O
  • 20. Copyright 2015 Kirk Pepperdine. All rights reserved gcLogEntries.stream().parallel(). 
 .map(applicationStoppedTimePattern::matcher) 
 .filter(Matcher::find) 
 .map(matcher -> matcher.group(2)) 
 .mapToDouble(Double::parseDouble) 
 .summaryStatistics(); parallelize stream
  • 21. Copyright 2015 Kirk Pepperdine. All rights reserved
  • 22. Copyright 2015 Kirk Pepperdine. All rights reserved The first time we tried, the imperative single threaded code
  • 23. Copyright 2015 Kirk Pepperdine. All rights reserved ran faster (????)
  • 24. Copyright 2015 Kirk Pepperdine. All rights reserved Flat profile of 8.70 secs (638 total ticks): ForkJoinPool.commonPool-worker-3 Compiled + native Method 60.8% 118 + 0 java.util.concurrent.ForkJoinTask.doExec Raw Profiler Output
  • 25. Copyright 2015 Kirk Pepperdine. All rights reserved Flat profile of 8.70 secs (638 total ticks): ForkJoinPool.commonPool-worker-3 Compiled + native Method 60.8% 118 + 0 java.util.concurrent.ForkJoinTask.doExec Raw Profiler Output Learned 2 things very quickly Parallel streams use Fork-Join Fork-Join comes with some significant over- head
  • 26. Copyright 2015 Kirk Pepperdine. All rights reserved Predicted that applcations using parallel streams would For other reasons…. run very very slowly
  • 27. Copyright 2015 Kirk Pepperdine. All rights reserved Then, witnessing it!
  • 28. Copyright 2015 Kirk Pepperdine. All rights reserved When to use Streams Tragedy of the commons Handoff costs CNPQ performance model Fork-Join
  • 29. Copyright 2015 Kirk Pepperdine. All rights reserved Tragidy of the Commons
  • 30. Copyright 2015 Kirk Pepperdine. All rights reserved You have a finite amount of hardware it might be in your best interest to grab it all if everyone behaves the same way…. Be a good neighbour
  • 31. Copyright 2015 Kirk Pepperdine. All rights reserved Handoff Costs It costs about ~80,000 clocks to handoff data between threads overhead = 80000*handoff rate/cycles 10%= 80000*handoff rate/2000000000 ~2500 handoffs/sec
  • 32. Copyright 2015 Kirk Pepperdine. All rights reserved CPNQ Performance Model C - number of submitters P - number of CPUs N - number of elements Q - cost of the operation
  • 33. Copyright 2015 Kirk Pepperdine. All rights reserved C/P/N/Q Need to amortize setup costs NQ needs to be large Q can often only be estimated N often should be > 10,000 elements P assumes CPU is the limiting resource
  • 34. Copyright 2015 Kirk Pepperdine. All rights reserved Fork-Join Support for Fork-Join added in Java 7 difficult coding idiom to master Streams make Fork-Join more reachable how fork-join works and performs is important to your latency picture
  • 35. Copyright 2015 Kirk Pepperdine. All rights reserved Implementation Used internally by a parallel stream break the stream up into chunks and submit each chunk as a ForkJoinTask apply filter().map().reduce() to each ForkJoinTask Calls ForkJoinTask invoke() and join() to retrieve results
  • 36. Copyright 2015 Kirk Pepperdine. All rights reserved Common Thread Pool Fork-Join by default uses a common thread pool default number of worker threads == number of logical cores - 1 Always contains at least one thread
  • 37. Copyright 2015 Kirk Pepperdine. All rights reserved Little’s Law Fork-Join uses a work queue work queue behavior can be modeled using Little’s Law Number of tasks in the system is the Arrival rate * average service time
  • 38. Copyright 2015 Kirk Pepperdine. All rights reserved Little’s Law Example System sees 400 TPS. It takes 100ms to process a request Number of tasks in system = 0.100 * 400 = 40 On an 8 core machine implies 39 Fork-Join tasks are sitting in queue accumulating dead time 40*100 = 4000 ms of which 3900 is dead time 97.5% of service time is in waiting
  • 39. Copyright 2015 Kirk Pepperdine. All rights reserved Normal Reaction if there is sufficient capacity then make the pool bigger else add capacity or tune to reduce strength of the dependency
  • 40. Copyright 2015 Kirk Pepperdine. All rights reserved Configuring Common Pool Size of common ForkJoinPool is Runtime.getRuntime().availableProcessors() - 1 Can configure things -Djava.util.concurrent.ForkJoinPool.common.parallelism=N -Djava.util.concurrent.ForkJoinPool.common.threadFactory -Djava.util.concurrent.ForkJoinPool.common.exceptionHandler
  • 41. Copyright 2015 Kirk Pepperdine. All rights reserved All Hands on Deck!!! Everyone is working together to get it done!
  • 42. Copyright 2015 Kirk Pepperdine. All rights reserved Resource Dependency If task is CPU bound, you can’t increase the size of the thread pool CPU may not be the limiting factor throughput is limited by another dependent resource I/O, shared variable (lock) Adding threads == increased latency predicted by Little’s Law
  • 43. Copyright 2015 Kirk Pepperdine. All rights reserved ForkJoinPool invoke ForkJoinPool.invoke(ForkJoinTask) uses the submitting thread as a worker If 100 threads all call invoke(), we would have 100+ForkJoinThreads exhausting the limiting resource, e.g. CPUs, IO, etc.
  • 44. Copyright 2015 Kirk Pepperdine. All rights reserved ForkJoinPool submit/get ForkJoinPool.submit(Callable).get() suspends the submitting thread If 100 jobs all call submit(), the work queue can become very long, thus adding latency
  • 45. Copyright 2015 Kirk Pepperdine. All rights reserved Our own ForkJoinPool When used inside a ForkJoinPool, the ForkJoinTask.fork() method uses the current pool ForkJoinPool ourOwnPool = new ForkJoinPool(10); ourOwnPool.invoke(() -> stream.parallel(). …
  • 46. Copyright 2015 Kirk Pepperdine. All rights reserved ForkJoinPool public void parallel() throws IOException { ForkJoinPool forkJoinPool = new ForkJoinPool(10); Stream<String> stream = Files.lines( new File(gcLogFileName).toPath()); forkJoinPool.submit(() -> stream.parallel()
 .map(applicationStoppedTimePattern::matcher)
 .filter(Matcher::find)
 .map(matcher -> matcher.group(2))
 .mapToDouble(Double::parseDouble)
 .summaryStatistics().toString()); }
  • 47. Copyright 2015 Kirk Pepperdine. All rights reserved ForkJoinPool Observability ForkJoinPool comes with no visibility need to instrument ForkJoinTask.invoke() gather needed from ForkJoinPool needed to feed into Little’s Law
  • 48. Copyright 2015 Kirk Pepperdine. All rights reserved Instrumenting ForkJoinPool We can get the statistics needed from ForkJoinPool needed for Little’s Law need to instrument ForkJoinTask::invoke() public final V invoke() { ForkJoinPool.common.getMonitor().submitTask(this); int s; if ((s = doInvoke() & DONE_MASK) != NORMAL) reportException(s); ForkJoinPool.common.getMonitor().retireTask(this); return getRawResult(); }
  • 49. Copyright 2015 Kirk Pepperdine. All rights reserved In an application where you have many parallel stream operations all running concurrently performance will be limited by the size of the common thread pool
  • 50. Copyright 2015 Kirk Pepperdine. All rights reserved Benchmark Alert!!!!!!
  • 51. Copyright 2015 Kirk Pepperdine. All rights reserved Performance Submitt log parsing to our own ForkJoinPool new ForkJoinPool(16).submit(() -> ……… ).get() new ForkJoinPool(8).submit(() -> ……… ).get() new ForkJoinPool(4).submit(() -> ……… ).get()
  • 52. Copyright 2015 Kirk Pepperdine. All rights reserved 16 worker threads 8 worker threads 4 worker threads
  • 53. Copyright 2015 Kirk Pepperdine. All rights reserved 0 75000 150000 225000 300000 Stream Parallel Flood Stream Flood Parallel
  • 54. Copyright 2015 Kirk Pepperdine. All rights reserved Going parallel might not give you the expected gains
  • 55. Copyright 2015 Kirk Pepperdine. All rights reserved You may not know this until you hit production!
  • 56. Copyright 2015 Kirk Pepperdine. All rights reserved Monitoring internals of JDK is important to understanding where bottlenecks are
  • 57. Copyright 2015 Kirk Pepperdine. All rights reserved JDK is not all that well instrumented
  • 58. Copyright 2015 Kirk Pepperdine. All rights reserved APIs have changed so you need to re-read the javadocs even for your old familiar classes
  • 59. Copyright 2015 Kirk Pepperdine. All rights reserved Performance Seminar www.kodewerk.com Java Performance Tuning, May 26-29, Chania Greece