SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
by Mario Fusco
mario.fusco@gmail.com
@mariofusco
Comparing different
concurrency models
on the JVM
Moore's
law
The number of transistors on integrated
circuits doubles approximately every two years
Now achieved
by increasing
the number
of cores
idle
This is what
typically
happens
in your
computer
Concurrency & Parallelism
Parallel programming
Running multiple tasks at
the same time
Concurrent programming
Managing concurrent requests
Both are hard!
The native Java concurrency model
Based on:
They are sometimes plain evil …
… and sometimes a necessary pain …
… but always the wrong default
Threads
Semaphores
SynchronizationLocks
What do you think when I say parallelism?
Threads
And what do you think when I say threads?
Locks
What are they for?
They prevent multiple threads to run in parallel
Do you see the problem?
Summing attendants ages (Threads)
class Blackboard {
int sum = 0;
int read() { return sum; }
void write(int value) { sum = value; }
}
class Attendee implements Runnable {
int age;
Blackboard blackboard;
public void run() {
synchronized(blackboard) {
int oldSum = blackboard.read();
int newSum = oldSum + age;
blackboard.write(newSum);
}
}
}
The Java Concurrency Bible
You know you're in big troubles when you feel
the need of taking this from your bookshelf
Don't call alien
methods while holding a lock
Threads – Good practices
Acquire multiple locks
in a fixed, global order
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
rwl.writeLock().tryLock(3L, TimeUnit.SECONDS);
Use interruptible locks instead of intrinsic synchronization
Avoid blocking using concurrent
data structures and atomic
variable when possible
Use thread pools instead of creating threads directly
Hold locks for the
shortest possible
amount of time
Learn Java Concurrency API
How you designed it
What happens in reality
Threads and Locks – Pros & Cons
+ “Close to the metal” → can be very efficient when
implemented correctly
+ Low abstraction level → widest range of applicability and high
degree of control
+ Threads and lock can be implemented in existing imperative
object-oriented languages with little effort
- Low abstraction level → threads-and-locks programming is HARD
and understanding the Java Memory Model even HARDER
- Inter-threads communication done with shared mutable state
leads to non-determinism
- Threads are a scarce resource
- It works only with shared-memory architectures → no support
for distributed memory → cannot be used to solve problems
that are too large to fit on a single system
- Writing multithreaded programs is difficult but testing them is
nearly impossible → a maintenance nightmare
Threads & Locks
Concurrent programming
Assembler
Programming
=
Patient: "Doctor, it hurts when I do this.”
Doctor: "Then stop doing it."
Do not try and fix the deadlock, that's
impossible. Instead, only try and realize
the truth.... there is no deadlock.
Then you will see it is not the deadlock
that needs fixing, it is only yourself.
What about Queues instead of Locks?
In reality actors are just a more structured and powerful way of
using queues. More on this later …
+ Better decoupling
+ Message passing
instead of shared memory
- High wake-up latency
- No built-in failure recovery
- Heavyweight
- Unidirectional
The cause of the problem …
Mutable state +
Parallel processing =
Non-determinism
Functional
Programming
Functional Programming
OOP makes code understandable
by encapsulating moving parts
FP makes code understandable
by minimizing moving parts
- Michael Feathers
OOP vs FP
Mutability
Parameter binding is about assigning names to things
Mutating variables is about assigning things to names
Does that second
one sound weird?
… well it's because
it IS weird
Dangers of mutable state (1)
public class DateParser {
private final DateFormat format =
new SimpleDateFormat("yyyy-MM-dd");
public Date parse(String s) throws ParseException {
return format.parse(s);
}
}
Hidden Mutable State
final == thread-safe ?
Dangers of mutable state (2)
public class Conference {
private final List<Attendee> attendees = new LinkedList<>();
public synchronized void addAttendee(Attendee a) {
attendees.add(a);
}
public synchronized Iterator<Attendee> getAttendeeIterator() {
return attendees.iterator();
}
}
Escaped Mutable State
synchronized == thread-safe ?
Summing attendants ages (Functional)
class Blackboard {
final int sum;
Blackboard(int sum) { this.sum = sum; }
}
class Attendee {
int age;
Attendee next;
public Blackboard addMyAge(Blackboard blackboard) {
final Blackboard b = new Blackboard(blackboard.sum + age);
return next == null ? b : next.addMyAge(b);
}
}
FP + Internal iteration = free parallelism
public int sumAges(List<Attendee> attendees) {
int total = 0;
for (Attendee a : attendees) {
total += a.getAge();
}
return total;
}
public int sumAges(List<Attendee> attendees) {
return attendees.stream()
.map(Attendee::getAge)
.reduce(0, Integer::sum);
}
External iteration
Internal iteration
FP + Internal iteration = free parallelism
public int sumAges(List<Attendee> attendees) {
int total = 0;
for (Attendee a : attendees) {
total += a.getAge();
}
return total;
}
public int sumAges(List<Attendee> attendees) {
return attendees.stream()
.map(Attendee::getAge)
.reduce(0, Integer::sum);
}
External iteration
Internal iteration
public int sumAges(List<Attendee> attendees) {
return attendees.parallelStream()
.map(Attendee::getAge)
.reduce(0, Integer::sum);
}
The best way to write parallel
applications is NOT to have
to think about parallelism
Parallel reduction – Divide and Conquer
Use Java 7 Fork/Join
framework under the
hood, but expose an
higher abstraction level
Using your own ForkJoinPool with
parallel Streams
public int sumAges(List<Attendee> attendees) {
return new ForkJoinPool(2).submit(() ->
attendees.parallelStream()
.map(Attendee::getAge)
.reduce(0, Integer::sum)
).join();
}
CompletableFuture<Integer> sum =
CompletableFuture.supplyAsync(() ->
attendees.parallelStream()
.map(Attendee::getAge)
.reduce(0, Integer::sum),
new ForkJoinPool(2));
}
Don't do this at home!!!
public static <T> void sort(List<T> list,
Comparator<? super T> c)
Essence of Functional Programming
Data and behaviors are the same thing!
Data
Behaviors
Collections.sort(persons,
(p1, p2) -> p1.getAge() – p2.getAge())
Map/Reduce is a FP pattern
public int sumAges(List<Attendee> attendees) {
return attendees.stream()
.map(Attendee::getAge)
.reduce(0, Integer::sum);
}
Do these methods' names remember you something?
Fast also because, when possible, Map/Reduce moves
computation (functions) to the data and not the opposite.
Functions – Pros & Cons
+ Immutability definitively prevents any non-determinism
+ Declarative programming style improves readability
→ focus on the “what” not on the “how”
+ Parallelizing functional (side-effect free) code can be trivially
easy in many cases
+ Better confidence that your program does what you think it does
+ Great support for distributed computation
- “Functional thinking” can be unfamiliar for many OOP developers
- Can be be less efficient than its imperative equivalent
- In memory managed environment (like the JVM) put a bigger
burden on the garbage collector
- Less control → how the computational tasks are splitted and
scheduled on threads is delegated to the library/framework
- Great abstraction for parallelism not for concurrency
Actors
Summing attendants ages (Actors)
class Blackboard extends UntypedActors {
int sum = 0;
public void onReceive(Object message) {
if (message instanceof Integer) {
sum += (Integer)message;
}
}
}
class Attendant {
int age;
Blackboard blackboard;
public void sendAge() {
blackboard.tell(age);
}
}
The way OOP is
implemented in most
common imperative
languages is probably
one of the biggest
misunderstanding in
the millenarian history
of engineering
This is Class Oriented Programming
Actors are the real OOP (Message Passing)
I'm sorry that I coined the term "objects", because it
gets many people to focus on the lesser idea. The big
idea is "messaging".
Alan Kay
Defensive programming Vs. Let it crash!
Throwing an exception in concurrent code will just simply blow
up the thread that currently executes the code that threw it:
1. There is no way to find out what went wrong, apart from
inspecting the stack trace
2. There is nothing you can do to recover from the problem
and bring back your system to a normal functioning
What’s wrong in trying to prevent errors?
Supervised actors
provide a clean error
recovery strategy
encouraging
non-defensive
programming
Actors – Pros & Cons
+ State is mutable but encapsulated → concurrency is
implemented with message flow between actors
+ Built-in fault tolerance through supervision
+ Not a scarce resource as threads → can have multiple actors for
each thread
+ Location transparency easily enables distributed programming
+ Actors map real-world domain model
- Untyped messages don't play well with Java's lack of pattern matching
- It's easy to violate state encapsulation → debugging can be hard
- Message immutability is vital but cannot be enforced in Java
- Actors are only useful if they produce side-effects
- Composition can be awkward
- Actors do not prevent deadlocks → it’s possible for two or more
actors to wait on one another for messages
The state quadrants
Mutable
Immutable
Shared
Unshared
Actors
Functional
Programming
Threads
Determinism
Non-determinism
Software Transactional Memory
Software Transactional Memory
An STM turns the Java heap into a transactional data set with
begin/commit/rollback semantics. Very much like a regular database.
It implements the first three letters in ACID; ACI:
Atomic → all or none of the changes made during a transaction get
applied
Consistent → a transaction has a consistent view of reality
Isolated → changes made by concurrent execution transactions are
not visible to each other
➢ A transaction is automatically retried when it runs into some
read or write conflict
➢ In this case a delay is used to prevent further contentions
➢ There shouldn’t be side-effects inside the transaction to avoid to
repeat them
Summing attendants ages (STM)
import org.multiverse.api.references.*;
import static org.multiverse.api.StmUtils.*;
public class Blackboard {
private final TxnRef<Date> lastUpdate;
private final TxnInteger sum = newTxnInteger(0);
public Blackboard() {
this.lastUpdate = newTxnRef<Date>(new Date());
}
public void sumAge(Attendant attendant) {
atomic(new Runnable() {
public void run() {
sum.inc(attendant.getAge());
lastUpdate.set(new Date());
}
});
}
}
STM – Pros & Cons
+ Eliminates a wide range of common problems related with
explicit synchronization
+ Optimistic and non-blocking
+ Many developers are already used to think in transactional terms
+ It's possible to compose multiple transactional blocks nesting
them in a higher level transaction
- Write collision are proportional to threads contention level
- Retries can be costly
- Unpredictable performance
- Transactional code has to be idempotent, no side-effects are
allowed
- No support for distribution
(Completable)Future
The Future interface was introduced in Java 5 to model an asynch
computation and then provide an handle to a result that will be
made available at some point in the future.
CompletableFuture introduced in Java 8 added
fluent composability, callbacks and more.
CompletableFuture
.supplyAsync(() -> shop.getPrice(product))
.thenCombine(CompletableFuture.supplyAsync(
() -> exchange.getRate(Money.EUR,
Money.USD)),
(price, rate) -> price * rate)
.thenAccept(System.out::println);
+ Non-blocking composition
+ Freely sharable
+ Can recover from failure
- Callback Hell
- Debugging can be hard
- Closing over mutable state
Reactive Programming
+ Non-blocking composition
with richer semantic
+ Event centric → async in nature
+ Can recover from failure
- Callback Hell
- Push instead of pull →
Inverted control flow
- Fast producer/slow consumer
→ May require blocking
Reactive programming consists in asynch processing and
combining streams of events ordered in time.
RxJava is a library, including a DSL, for composing asynch and
event-based programs using observable sequences
Observable<Stock> stockFeed =
Observable.interval(1, TimeUnit.SECONDS)
.map(i -> StockServer.fetch(symbol));
stockFeed.subscribe(System.out::println);
Wrap up – There's No Silver Bullet
One
size
does
NOT
fit
all
➢ Concurrency and parallelism
will be increasingly
important in the near future
➢ Using threads & locks by
default is (at best) premature
optimization
➢ There are many different
concurrency models with
different characteristic
➢ Know them all and choose
the one that best fit the
problem at hand
Wrap up – The Zen of Concurrency
Avoid shared mutability → if there is no clear way
to avoid mutability, then favor isolated mutability
Sequential programming idioms (e.g. external
iteration) and tricks (e.g. reusing variables) are
detrimental for parallelization
Prototype different solutions with different
concurrency models and discover their strengths
and weaknesses
Premature optimization is evil especially in
concurrent programming → Make it right first
and only AFTER make it faster
Poly-paradigm programming is more effective
than polyglot → you can experiment all those
different concurrency models in plain Java
Strive for immutability → Make fields and local variables final by
default and make an exception only when strictly required
Suggested readings
Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Q A
Thanks … Questions?

Contenu connexe

Tendances

Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningCarol McDonald
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015Constantine Mars
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and SimpleBen Mabey
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 

Tendances (20)

Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 

En vedette

OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJosé Paumard
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep diveMario Fusco
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageMario Fusco
 
Comparing implementations of the actor model
Comparing implementations of the actor modelComparing implementations of the actor model
Comparing implementations of the actor modelJim Roepcke
 
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...Yusuke Matsubara
 
The Joy Of Functional Programming
The Joy Of Functional ProgrammingThe Joy Of Functional Programming
The Joy Of Functional Programmingjasondew
 
Massively Scaleable .NET Web Services with Project Orleans
Massively Scaleable .NET Web Services with Project OrleansMassively Scaleable .NET Web Services with Project Orleans
Massively Scaleable .NET Web Services with Project OrleansNewman Hunter
 
MicroProfile Panel - Sept 2016
MicroProfile Panel - Sept 2016MicroProfile Panel - Sept 2016
MicroProfile Panel - Sept 2016Ray Ploski
 
Expert Java Day: Java concurrency
Expert Java Day: Java concurrencyExpert Java Day: Java concurrency
Expert Java Day: Java concurrencyPavel Titkov
 

En vedette (20)

OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Model storming
Model stormingModel storming
Model storming
 
Transactions redefined
Transactions redefinedTransactions redefined
Transactions redefined
 
Comparing implementations of the actor model
Comparing implementations of the actor modelComparing implementations of the actor model
Comparing implementations of the actor model
 
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...
K-repeating Substrings: a String-Algorithmic Approach to Privacy-Preserving P...
 
Uses of java
Uses of javaUses of java
Uses of java
 
The Joy Of Functional Programming
The Joy Of Functional ProgrammingThe Joy Of Functional Programming
The Joy Of Functional Programming
 
24 Multithreaded Algorithms
24 Multithreaded Algorithms24 Multithreaded Algorithms
24 Multithreaded Algorithms
 
Massively Scaleable .NET Web Services with Project Orleans
Massively Scaleable .NET Web Services with Project OrleansMassively Scaleable .NET Web Services with Project Orleans
Massively Scaleable .NET Web Services with Project Orleans
 
MicroProfile Panel - Sept 2016
MicroProfile Panel - Sept 2016MicroProfile Panel - Sept 2016
MicroProfile Panel - Sept 2016
 
Expert Java Day: Java concurrency
Expert Java Day: Java concurrencyExpert Java Day: Java concurrency
Expert Java Day: Java concurrency
 

Similaire à Comparing different concurrency models on the JVM

Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Codemotion
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Evolution of JDK Tools for Multithreaded Programming
Evolution of JDK Tools for Multithreaded ProgrammingEvolution of JDK Tools for Multithreaded Programming
Evolution of JDK Tools for Multithreaded ProgrammingGlobalLogic Ukraine
 
Clustered PHP - DC PHP 2009
Clustered PHP - DC PHP 2009Clustered PHP - DC PHP 2009
Clustered PHP - DC PHP 2009marcelesser
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futureTakayuki Muranushi
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfKrystian Zybała
 
Migration To Multi Core - Parallel Programming Models
Migration To Multi Core - Parallel Programming ModelsMigration To Multi Core - Parallel Programming Models
Migration To Multi Core - Parallel Programming ModelsZvi Avraham
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrencyaviade
 
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]Luigi Lauro
 
Luigi lauro thread with care (concurrency pitfalls in java)
Luigi lauro   thread with care (concurrency pitfalls in java)Luigi lauro   thread with care (concurrency pitfalls in java)
Luigi lauro thread with care (concurrency pitfalls in java)Codecamp Romania
 

Similaire à Comparing different concurrency models on the JVM (20)

Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Evolution of JDK Tools for Multithreaded Programming
Evolution of JDK Tools for Multithreaded ProgrammingEvolution of JDK Tools for Multithreaded Programming
Evolution of JDK Tools for Multithreaded Programming
 
Clustered PHP - DC PHP 2009
Clustered PHP - DC PHP 2009Clustered PHP - DC PHP 2009
Clustered PHP - DC PHP 2009
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Java Threading
Java ThreadingJava Threading
Java Threading
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Migration To Multi Core - Parallel Programming Models
Migration To Multi Core - Parallel Programming ModelsMigration To Multi Core - Parallel Programming Models
Migration To Multi Core - Parallel Programming Models
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
 
Dsys guide37
Dsys guide37Dsys guide37
Dsys guide37
 
Luigi lauro thread with care (concurrency pitfalls in java)
Luigi lauro   thread with care (concurrency pitfalls in java)Luigi lauro   thread with care (concurrency pitfalls in java)
Luigi lauro thread with care (concurrency pitfalls in java)
 
Dev381.Pp
Dev381.PpDev381.Pp
Dev381.Pp
 
Java multi thread programming on cmp system
Java multi thread programming on cmp systemJava multi thread programming on cmp system
Java multi thread programming on cmp system
 

Plus de Mario Fusco

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automationMario Fusco
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 

Plus de Mario Fusco (9)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Lazy java
Lazy javaLazy java
Lazy java
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 

Dernier

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 

Dernier (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 

Comparing different concurrency models on the JVM

  • 1. by Mario Fusco mario.fusco@gmail.com @mariofusco Comparing different concurrency models on the JVM
  • 2. Moore's law The number of transistors on integrated circuits doubles approximately every two years Now achieved by increasing the number of cores idle
  • 3.
  • 4.
  • 6. Concurrency & Parallelism Parallel programming Running multiple tasks at the same time Concurrent programming Managing concurrent requests Both are hard!
  • 7. The native Java concurrency model Based on: They are sometimes plain evil … … and sometimes a necessary pain … … but always the wrong default Threads Semaphores SynchronizationLocks
  • 8. What do you think when I say parallelism? Threads And what do you think when I say threads? Locks What are they for? They prevent multiple threads to run in parallel Do you see the problem?
  • 9. Summing attendants ages (Threads) class Blackboard { int sum = 0; int read() { return sum; } void write(int value) { sum = value; } } class Attendee implements Runnable { int age; Blackboard blackboard; public void run() { synchronized(blackboard) { int oldSum = blackboard.read(); int newSum = oldSum + age; blackboard.write(newSum); } } }
  • 10. The Java Concurrency Bible You know you're in big troubles when you feel the need of taking this from your bookshelf
  • 11. Don't call alien methods while holding a lock Threads – Good practices Acquire multiple locks in a fixed, global order ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); rwl.writeLock().tryLock(3L, TimeUnit.SECONDS); Use interruptible locks instead of intrinsic synchronization Avoid blocking using concurrent data structures and atomic variable when possible Use thread pools instead of creating threads directly Hold locks for the shortest possible amount of time Learn Java Concurrency API
  • 13. What happens in reality
  • 14. Threads and Locks – Pros & Cons + “Close to the metal” → can be very efficient when implemented correctly + Low abstraction level → widest range of applicability and high degree of control + Threads and lock can be implemented in existing imperative object-oriented languages with little effort - Low abstraction level → threads-and-locks programming is HARD and understanding the Java Memory Model even HARDER - Inter-threads communication done with shared mutable state leads to non-determinism - Threads are a scarce resource - It works only with shared-memory architectures → no support for distributed memory → cannot be used to solve problems that are too large to fit on a single system - Writing multithreaded programs is difficult but testing them is nearly impossible → a maintenance nightmare
  • 15. Threads & Locks Concurrent programming Assembler Programming = Patient: "Doctor, it hurts when I do this.” Doctor: "Then stop doing it."
  • 16. Do not try and fix the deadlock, that's impossible. Instead, only try and realize the truth.... there is no deadlock. Then you will see it is not the deadlock that needs fixing, it is only yourself.
  • 17. What about Queues instead of Locks? In reality actors are just a more structured and powerful way of using queues. More on this later … + Better decoupling + Message passing instead of shared memory - High wake-up latency - No built-in failure recovery - Heavyweight - Unidirectional
  • 18. The cause of the problem … Mutable state + Parallel processing = Non-determinism Functional Programming
  • 20. OOP makes code understandable by encapsulating moving parts FP makes code understandable by minimizing moving parts - Michael Feathers OOP vs FP
  • 21. Mutability Parameter binding is about assigning names to things Mutating variables is about assigning things to names Does that second one sound weird? … well it's because it IS weird
  • 22. Dangers of mutable state (1) public class DateParser { private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); public Date parse(String s) throws ParseException { return format.parse(s); } } Hidden Mutable State final == thread-safe ?
  • 23. Dangers of mutable state (2) public class Conference { private final List<Attendee> attendees = new LinkedList<>(); public synchronized void addAttendee(Attendee a) { attendees.add(a); } public synchronized Iterator<Attendee> getAttendeeIterator() { return attendees.iterator(); } } Escaped Mutable State synchronized == thread-safe ?
  • 24. Summing attendants ages (Functional) class Blackboard { final int sum; Blackboard(int sum) { this.sum = sum; } } class Attendee { int age; Attendee next; public Blackboard addMyAge(Blackboard blackboard) { final Blackboard b = new Blackboard(blackboard.sum + age); return next == null ? b : next.addMyAge(b); } }
  • 25. FP + Internal iteration = free parallelism public int sumAges(List<Attendee> attendees) { int total = 0; for (Attendee a : attendees) { total += a.getAge(); } return total; } public int sumAges(List<Attendee> attendees) { return attendees.stream() .map(Attendee::getAge) .reduce(0, Integer::sum); } External iteration Internal iteration
  • 26. FP + Internal iteration = free parallelism public int sumAges(List<Attendee> attendees) { int total = 0; for (Attendee a : attendees) { total += a.getAge(); } return total; } public int sumAges(List<Attendee> attendees) { return attendees.stream() .map(Attendee::getAge) .reduce(0, Integer::sum); } External iteration Internal iteration public int sumAges(List<Attendee> attendees) { return attendees.parallelStream() .map(Attendee::getAge) .reduce(0, Integer::sum); } The best way to write parallel applications is NOT to have to think about parallelism
  • 27. Parallel reduction – Divide and Conquer Use Java 7 Fork/Join framework under the hood, but expose an higher abstraction level
  • 28. Using your own ForkJoinPool with parallel Streams public int sumAges(List<Attendee> attendees) { return new ForkJoinPool(2).submit(() -> attendees.parallelStream() .map(Attendee::getAge) .reduce(0, Integer::sum) ).join(); } CompletableFuture<Integer> sum = CompletableFuture.supplyAsync(() -> attendees.parallelStream() .map(Attendee::getAge) .reduce(0, Integer::sum), new ForkJoinPool(2)); } Don't do this at home!!!
  • 29. public static <T> void sort(List<T> list, Comparator<? super T> c) Essence of Functional Programming Data and behaviors are the same thing! Data Behaviors Collections.sort(persons, (p1, p2) -> p1.getAge() – p2.getAge())
  • 30. Map/Reduce is a FP pattern public int sumAges(List<Attendee> attendees) { return attendees.stream() .map(Attendee::getAge) .reduce(0, Integer::sum); } Do these methods' names remember you something? Fast also because, when possible, Map/Reduce moves computation (functions) to the data and not the opposite.
  • 31. Functions – Pros & Cons + Immutability definitively prevents any non-determinism + Declarative programming style improves readability → focus on the “what” not on the “how” + Parallelizing functional (side-effect free) code can be trivially easy in many cases + Better confidence that your program does what you think it does + Great support for distributed computation - “Functional thinking” can be unfamiliar for many OOP developers - Can be be less efficient than its imperative equivalent - In memory managed environment (like the JVM) put a bigger burden on the garbage collector - Less control → how the computational tasks are splitted and scheduled on threads is delegated to the library/framework - Great abstraction for parallelism not for concurrency
  • 33. Summing attendants ages (Actors) class Blackboard extends UntypedActors { int sum = 0; public void onReceive(Object message) { if (message instanceof Integer) { sum += (Integer)message; } } } class Attendant { int age; Blackboard blackboard; public void sendAge() { blackboard.tell(age); } }
  • 34. The way OOP is implemented in most common imperative languages is probably one of the biggest misunderstanding in the millenarian history of engineering This is Class Oriented Programming Actors are the real OOP (Message Passing)
  • 35. I'm sorry that I coined the term "objects", because it gets many people to focus on the lesser idea. The big idea is "messaging". Alan Kay
  • 36. Defensive programming Vs. Let it crash!
  • 37. Throwing an exception in concurrent code will just simply blow up the thread that currently executes the code that threw it: 1. There is no way to find out what went wrong, apart from inspecting the stack trace 2. There is nothing you can do to recover from the problem and bring back your system to a normal functioning What’s wrong in trying to prevent errors? Supervised actors provide a clean error recovery strategy encouraging non-defensive programming
  • 38. Actors – Pros & Cons + State is mutable but encapsulated → concurrency is implemented with message flow between actors + Built-in fault tolerance through supervision + Not a scarce resource as threads → can have multiple actors for each thread + Location transparency easily enables distributed programming + Actors map real-world domain model - Untyped messages don't play well with Java's lack of pattern matching - It's easy to violate state encapsulation → debugging can be hard - Message immutability is vital but cannot be enforced in Java - Actors are only useful if they produce side-effects - Composition can be awkward - Actors do not prevent deadlocks → it’s possible for two or more actors to wait on one another for messages
  • 41. Software Transactional Memory An STM turns the Java heap into a transactional data set with begin/commit/rollback semantics. Very much like a regular database. It implements the first three letters in ACID; ACI: Atomic → all or none of the changes made during a transaction get applied Consistent → a transaction has a consistent view of reality Isolated → changes made by concurrent execution transactions are not visible to each other ➢ A transaction is automatically retried when it runs into some read or write conflict ➢ In this case a delay is used to prevent further contentions ➢ There shouldn’t be side-effects inside the transaction to avoid to repeat them
  • 42. Summing attendants ages (STM) import org.multiverse.api.references.*; import static org.multiverse.api.StmUtils.*; public class Blackboard { private final TxnRef<Date> lastUpdate; private final TxnInteger sum = newTxnInteger(0); public Blackboard() { this.lastUpdate = newTxnRef<Date>(new Date()); } public void sumAge(Attendant attendant) { atomic(new Runnable() { public void run() { sum.inc(attendant.getAge()); lastUpdate.set(new Date()); } }); } }
  • 43. STM – Pros & Cons + Eliminates a wide range of common problems related with explicit synchronization + Optimistic and non-blocking + Many developers are already used to think in transactional terms + It's possible to compose multiple transactional blocks nesting them in a higher level transaction - Write collision are proportional to threads contention level - Retries can be costly - Unpredictable performance - Transactional code has to be idempotent, no side-effects are allowed - No support for distribution
  • 44. (Completable)Future The Future interface was introduced in Java 5 to model an asynch computation and then provide an handle to a result that will be made available at some point in the future. CompletableFuture introduced in Java 8 added fluent composability, callbacks and more. CompletableFuture .supplyAsync(() -> shop.getPrice(product)) .thenCombine(CompletableFuture.supplyAsync( () -> exchange.getRate(Money.EUR, Money.USD)), (price, rate) -> price * rate) .thenAccept(System.out::println); + Non-blocking composition + Freely sharable + Can recover from failure - Callback Hell - Debugging can be hard - Closing over mutable state
  • 45. Reactive Programming + Non-blocking composition with richer semantic + Event centric → async in nature + Can recover from failure - Callback Hell - Push instead of pull → Inverted control flow - Fast producer/slow consumer → May require blocking Reactive programming consists in asynch processing and combining streams of events ordered in time. RxJava is a library, including a DSL, for composing asynch and event-based programs using observable sequences Observable<Stock> stockFeed = Observable.interval(1, TimeUnit.SECONDS) .map(i -> StockServer.fetch(symbol)); stockFeed.subscribe(System.out::println);
  • 46. Wrap up – There's No Silver Bullet One size does NOT fit all ➢ Concurrency and parallelism will be increasingly important in the near future ➢ Using threads & locks by default is (at best) premature optimization ➢ There are many different concurrency models with different characteristic ➢ Know them all and choose the one that best fit the problem at hand
  • 47. Wrap up – The Zen of Concurrency Avoid shared mutability → if there is no clear way to avoid mutability, then favor isolated mutability Sequential programming idioms (e.g. external iteration) and tricks (e.g. reusing variables) are detrimental for parallelization Prototype different solutions with different concurrency models and discover their strengths and weaknesses Premature optimization is evil especially in concurrent programming → Make it right first and only AFTER make it faster Poly-paradigm programming is more effective than polyglot → you can experiment all those different concurrency models in plain Java Strive for immutability → Make fields and local variables final by default and make an exception only when strictly required
  • 49. Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco Q A Thanks … Questions?