SlideShare a Scribd company logo
Java 8 Concurrency Abstractions
-Exploring Java 8 concurrency abstractions
-Comparing against Java 7 concurrency
abstractions
Agenda
1. Overview of concurrency libraries added in JDK8
2. Asynchronous result processing
3. CompletableFuture (Vs classical Future)
4. StampedLock (Vs ReadWriteLock)
? Pre-requisites: Assumes Lambda, Method Ref,.
Functional Interfaces (Supplier, Consumer,
Function etc)
Myself
• GlobalLogic India Ltd, Bangalore
• Concurrency Enthusiast (Golang, Java)
• Servlet 4.0 Spec (JSR 369), JavaEE8
• JavaCodeGeeks
• Dzone
1. Concurrency Overview
– Adders And Accumulators
– New Methods to ConcurrentHashMap
– Common Pool
Asynchronous Result Processing
1. Overview of concurrency libraries added in
JDK8
2. Asynchronous result processing
3. CompletableFuture (Vs classical Future)
4. StampedLock (Vs ReadWriteLock)
Asynchronous Result Processing
– Synchronous
– Not Synchronous, Asynchronous [Java 5]
– Asynchronous and Reactive [Java 8]
Client Server
Request
Server
Proc...
Client Blocked
Response
Synchronous
Client Server
Request
Server
Proc...
Ctrl ret. immed
Asynchronous
Client polls - X
Client polls - Y
Response
Client Server
Request
Server
Proc...
Response Push
Ctrl ret. immed
Asynchronous + Reactive
Agenda
1. Overview of concurrency libraries added in
JDK8
2. Asynchronous result processing
3. CompletableFuture (Vs classical Future)
4. StampedLock (Vs ReadWriteLock)
Classical Future
• An interface in java.util.concurrent pkg
• FutureTask is the concrete implementation
• Represents the result of an async processing.
• Utility Methods with the interface:
– isDone()
– isCancelled()
– cancel(boolean mayInterruptIfRunning)
• Lets see it in action!
Classical Future continued 3
• Future programming model:
ExecutorService pool = ...
Future<Double> bankBalance=pool.submit(()->{
Thread.sleep(5000L);//sim processing time
return bankBalance;
});
try{
double balance = bankBalance.get(); //blocking call
}catch(InterruptedException ignore){}
• Work around:
– May spin around and check with isDone() or isCancelled();
– Use CompletableFuture!
CompletableFuture
• A class in java.util.concurrent package
• Implements CompletionStage and Future
interfaces (both in java.util.concurrent pkgs)
• Since CompletableFuture implements Future,
it can be used classically – blockingly!
• CompletionStage is the interface which
provides all the reactive constructs; fat
interface
CompletableFuture Reactive Usage
• CompletableFuture Programming Model.
• Get a CompletableFuture instance:
– Static Factory
• CompletableFuture.supplyAsync(Supplier) //one variant
• CompletableFuture<Double>bankBalanceFut =
CompletableFuture.supplyAsync(()->{
return getBankBalance(); //long running task
}) //args Supplier instance.
• Wire reactions:
• bankBalanceFut.thenAccept((balance)->{ //three variants;
System.out.println(“Available balance: ”+balance)
}) //args Consumer inst.
• Lets try this!
supplyAsync(...) Variants
• publicstatic <U> CompletableFuture<U> supplyAsync(Sup
plier<U> supplier)
– Uses ForkJoinPool.commonPool();
• publicstatic <U> CompletableFuture<U> supplyAsync(Sup
plier<U> supplier, Executor executor)
– Uses the passed into Executor as the thread pool
• supplyAsync’s counterpart – runAsync(...)
– Takes Runnable instead of Supplier
– Returns CompletableFuture<Void>
– Calling get() would return null
thenAccept(...) Variants
• public CompletableFuture<Void> thenAccept(Consumer<?
super T> action)
• public CompletableFuture<Void> thenAcceptAsync(Consumer
<? super T> action)
• public CompletableFuture<Void> thenAcceptAsync(Consumer
<? super T> action, Executor executor)
More into piping Reactions
• Fluent API helps piping reactions.
• supplyAsync(Supplier)
.whenComplete(BiConsumer)//res, err
.thenApply(Function)
.thenAccept(Consumer)
.thenRun(Runnable)
Other Important Piping APIs - 1
• Composition:
public <U> CompletableFuture<U> thenCompose(Function<?
super T,? extends CompletionStage<U>> fn)
(This)
CompletionStage<U>
Function(? super T, ?
extends
CompletionStage<U>)
CompletionStage<T>
Other Important Piping APIs - 2
• Combination:
public <U,V> CompletableFuture<V> thenCombine(Completio
nStage<? extends U> other, BiFunction<? super T,? super U,?
extends V> fn)
(This)
CompletionStage
<U>
(Other)
CompletionStage
<V>
BiFunction(?
super T, ? Super
U, ? extends V)
CompletionStage
<T>
How we leveraged the power of
CompletableFuture
• Use Case #1 (Remote Serivces)
– Two remote services.
– Both replicate service
– We needed anyone to respond; faster! (acceptEither)
– Lets simulate what we did!
– Can be extended easily to any number of services!
• public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
How we leveraged the power of
CompletableFuture - 2
• Use Case #2 (update UI after File FTP completes)
– Application UI uploads file; not on UI thread;
– UI thread is not blocked; it reacts whenever FTP is completed.
– CompletableFuture<FTPStatus> ftp = CompletableFuture.supplyAsync(()->{
return FTPClient.uploadFile(file);
});
ftp . whenComplete((ftpStatus,error)->{ //takes BiConsumer; alt. handle takes
//BiFunction
if (error == null){
//grab UI thread and update of successful FTP
} else{
// grab UI thread and update of failure FTP
}
})
Creating APIs to return
CompletableFuture
• How to expose CompletableFuture APIs for Clients!
• Instantiate CompletableFuture
• Set result to it asynchronously.
public CompletableFuture<String> getPageContent(URL url){
CompletableFuture<String> futurePage =
CompletableFuture<>();
Runnable task = ()->{
try{
String htmlContent = fetchPageContent(url); //long running
futurePage.complete(htmlContent); //not with classicFuture
// this is why it is CompletableFut.
}catch(Throwable th){
futurePage.completeExceptionally(th); //set complete exceptionally
}
};
exec.submit(task);
return futurePage;
}
Exception Handling
• Exception Handling in CompletableFuture:
– exceptionally()
– handle()
– whenComplete()
• Time for Code  !
ReentrantReadWriteLock
Precursor to StampedLock
• java.util.concurrent.locks.ReentrantReadWriteLock
– Pessimistic Write
– Pessimistic Read
– No Optimistic Locking
ReentrantReadWriteLock
• ReentrantReadWriteLock Usage:
private SomeClass theData;
pri final ReadWriteLock myLocks =
new ReentrantReadWriteLock(true);
public void write(){
myLocks.writeLock().lock();
try{theData.write();}
finally{myLocks.writeLock().unlock();}
}
public void read(){
myLocks.readLock().lock();
try{theData.read();}
finally{myLocks.readLock().unlock();}
}
StampedLock
• JDK8 addition into package
java.util.concurrent.locks
– Works with versions of StampedLock – the
“Stamp”
– Modes
• Pessimistic Write
• Pessimistic Read
• Optimistic Read! (Optimization)
Pessimistic StampedLocking
Pessimistic Usage:
private SomeClass theData;
private final StampedLock lock=
new StampedLock(true);
public void write(){
long stamp = lock.writeLock();
try{theData.write();}
finally{lock.writeLock(stamp);}
}
public void read(){
long stamp = lock.readLock();
try{theData.read();}
finally{lock.unlockRead(stamp);}
}
Optimistic StampedLock
Optimistic usage:
• try OptimisticRead
• Validate optimisticRead stamp
• Based on the validation take further action.
• Lets Try!!!
private int p1, p2
StampedLock lock = new StampedLock();
public void read(){
long stamp = lock.tryOptimisticRead();
int l1 = p1;
int l2 = p2;
if(lock.validate(stamp)){ //validate the stamp (version)
process(l1, l2);
}else{
stamp = lock.readLock()//acquire pessimistic locks
try{l1 = p1;
l2= p2;
process(l1, l2);
}
finally{lock.unlockRead(stamp)}
}
}
Conclusion
• CompletableFuture is powerful
– Explore more
– Write your own RxJava 
• StampedLock is more efficient and optimized
for particular use cases!
Java 8 concurrency abstractions

More Related Content

What's hot

Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
Viral Solani
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
Yakov Fain
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
Azukisoft Pte Ltd
 
Apache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the boxApache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the box
Claus Ibsen
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
Raf Kewl
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
Sencha
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
Bukhori Aqid
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?Oliver Gierke
 
Advanced Server Integration with Data and Direct
Advanced Server Integration with Data and DirectAdvanced Server Integration with Data and Direct
Advanced Server Integration with Data and Direct
Sencha
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
Jonathan Goode
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
Oliver Gierke
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
Soheil Khodayari
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
Simon Funk
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Red Hat Developers
 
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
2014-02-20 | Akka Concurrency (Vienna Scala User Group)2014-02-20 | Akka Concurrency (Vienna Scala User Group)
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
Dominik Gruber
 
The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
krivachy
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello Production
Joe Ferguson
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
Vikas Chauhan
 

What's hot (20)

Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Apache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the boxApache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the box
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?
 
Advanced Server Integration with Data and Direct
Advanced Server Integration with Data and DirectAdvanced Server Integration with Data and Direct
Advanced Server Integration with Data and Direct
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
 
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
2014-02-20 | Akka Concurrency (Vienna Scala User Group)2014-02-20 | Akka Concurrency (Vienna Scala User Group)
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
 
The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello Production
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 

Viewers also liked

Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
CodeOps Technologies LLP
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
CodeOps Technologies LLP
 
Better java with design
Better java with designBetter java with design
Better java with design
Narayann Swaami
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
CodeOps Technologies LLP
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture
CodeOps Technologies LLP
 
7 best quotes on dev ops
7 best quotes on dev ops7 best quotes on dev ops
7 best quotes on dev ops
CodeOps Technologies LLP
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native Development
CodeOps Technologies LLP
 
Introduction to chef
Introduction to chefIntroduction to chef
Introduction to chef
Krishna Kishore
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
CodeOps Technologies LLP
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
CodeOps Technologies LLP
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
CodeOps Technologies LLP
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
CodeOps Technologies LLP
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)
Heartin Jacob
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous Delivery
Murughan Palaniachari
 
DevOps Toolchain v1.0
DevOps Toolchain v1.0DevOps Toolchain v1.0
DevOps Toolchain v1.0
Giragadurai Vallirajan
 
DevOps game marshmallow challenge
DevOps game marshmallow challengeDevOps game marshmallow challenge
DevOps game marshmallow challenge
Murughan Palaniachari
 
Effective DB Interaction
Effective DB Interaction Effective DB Interaction
Effective DB Interaction
CodeOps Technologies LLP
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 

Viewers also liked (20)

Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
 
Better java with design
Better java with designBetter java with design
Better java with design
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture
 
7 best quotes on dev ops
7 best quotes on dev ops7 best quotes on dev ops
7 best quotes on dev ops
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native Development
 
Introduction to chef
Introduction to chefIntroduction to chef
Introduction to chef
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous Delivery
 
DevOps Toolchain v1.0
DevOps Toolchain v1.0DevOps Toolchain v1.0
DevOps Toolchain v1.0
 
DevOps game marshmallow challenge
DevOps game marshmallow challengeDevOps game marshmallow challenge
DevOps game marshmallow challenge
 
Effective DB Interaction
Effective DB Interaction Effective DB Interaction
Effective DB Interaction
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 

Similar to Java 8 concurrency abstractions

What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
kshanth2101
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8EPAM_Systems_Bulgaria
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
JavaEE Trainers
 
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
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
Geoff Ballinger
 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013
eamonnlong
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
vorfeed chen
 
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir MeetupCachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Abel Muíño
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen Wang
 
EmberJS BucharestJS
EmberJS BucharestJSEmberJS BucharestJS
EmberJS BucharestJS
Remus Rusanu
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
Knoldus Inc.
 
Reactive solutions using java 9 and spring reactor
Reactive solutions using java 9 and spring reactorReactive solutions using java 9 and spring reactor
Reactive solutions using java 9 and spring reactor
OrenEzer1
 

Similar to Java 8 concurrency abstractions (20)

What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Java 9
Java 9Java 9
Java 9
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
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
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir MeetupCachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
 
EmberJS BucharestJS
EmberJS BucharestJSEmberJS BucharestJS
EmberJS BucharestJS
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
Reactive solutions using java 9 and spring reactor
Reactive solutions using java 9 and spring reactorReactive solutions using java 9 and spring reactor
Reactive solutions using java 9 and spring reactor
 

Recently uploaded

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 

Recently uploaded (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 

Java 8 concurrency abstractions

  • 1. Java 8 Concurrency Abstractions -Exploring Java 8 concurrency abstractions -Comparing against Java 7 concurrency abstractions
  • 2. Agenda 1. Overview of concurrency libraries added in JDK8 2. Asynchronous result processing 3. CompletableFuture (Vs classical Future) 4. StampedLock (Vs ReadWriteLock) ? Pre-requisites: Assumes Lambda, Method Ref,. Functional Interfaces (Supplier, Consumer, Function etc)
  • 3. Myself • GlobalLogic India Ltd, Bangalore • Concurrency Enthusiast (Golang, Java) • Servlet 4.0 Spec (JSR 369), JavaEE8 • JavaCodeGeeks • Dzone
  • 4. 1. Concurrency Overview – Adders And Accumulators – New Methods to ConcurrentHashMap – Common Pool
  • 5. Asynchronous Result Processing 1. Overview of concurrency libraries added in JDK8 2. Asynchronous result processing 3. CompletableFuture (Vs classical Future) 4. StampedLock (Vs ReadWriteLock)
  • 6. Asynchronous Result Processing – Synchronous – Not Synchronous, Asynchronous [Java 5] – Asynchronous and Reactive [Java 8] Client Server Request Server Proc... Client Blocked Response Synchronous Client Server Request Server Proc... Ctrl ret. immed Asynchronous Client polls - X Client polls - Y Response Client Server Request Server Proc... Response Push Ctrl ret. immed Asynchronous + Reactive
  • 7. Agenda 1. Overview of concurrency libraries added in JDK8 2. Asynchronous result processing 3. CompletableFuture (Vs classical Future) 4. StampedLock (Vs ReadWriteLock)
  • 8. Classical Future • An interface in java.util.concurrent pkg • FutureTask is the concrete implementation • Represents the result of an async processing. • Utility Methods with the interface: – isDone() – isCancelled() – cancel(boolean mayInterruptIfRunning) • Lets see it in action!
  • 9. Classical Future continued 3 • Future programming model: ExecutorService pool = ... Future<Double> bankBalance=pool.submit(()->{ Thread.sleep(5000L);//sim processing time return bankBalance; }); try{ double balance = bankBalance.get(); //blocking call }catch(InterruptedException ignore){} • Work around: – May spin around and check with isDone() or isCancelled(); – Use CompletableFuture!
  • 10. CompletableFuture • A class in java.util.concurrent package • Implements CompletionStage and Future interfaces (both in java.util.concurrent pkgs) • Since CompletableFuture implements Future, it can be used classically – blockingly! • CompletionStage is the interface which provides all the reactive constructs; fat interface
  • 11. CompletableFuture Reactive Usage • CompletableFuture Programming Model. • Get a CompletableFuture instance: – Static Factory • CompletableFuture.supplyAsync(Supplier) //one variant • CompletableFuture<Double>bankBalanceFut = CompletableFuture.supplyAsync(()->{ return getBankBalance(); //long running task }) //args Supplier instance. • Wire reactions: • bankBalanceFut.thenAccept((balance)->{ //three variants; System.out.println(“Available balance: ”+balance) }) //args Consumer inst. • Lets try this!
  • 12. supplyAsync(...) Variants • publicstatic <U> CompletableFuture<U> supplyAsync(Sup plier<U> supplier) – Uses ForkJoinPool.commonPool(); • publicstatic <U> CompletableFuture<U> supplyAsync(Sup plier<U> supplier, Executor executor) – Uses the passed into Executor as the thread pool • supplyAsync’s counterpart – runAsync(...) – Takes Runnable instead of Supplier – Returns CompletableFuture<Void> – Calling get() would return null
  • 13. thenAccept(...) Variants • public CompletableFuture<Void> thenAccept(Consumer<? super T> action) • public CompletableFuture<Void> thenAcceptAsync(Consumer <? super T> action) • public CompletableFuture<Void> thenAcceptAsync(Consumer <? super T> action, Executor executor)
  • 14. More into piping Reactions • Fluent API helps piping reactions. • supplyAsync(Supplier) .whenComplete(BiConsumer)//res, err .thenApply(Function) .thenAccept(Consumer) .thenRun(Runnable)
  • 15. Other Important Piping APIs - 1 • Composition: public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn) (This) CompletionStage<U> Function(? super T, ? extends CompletionStage<U>) CompletionStage<T>
  • 16. Other Important Piping APIs - 2 • Combination: public <U,V> CompletableFuture<V> thenCombine(Completio nStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) (This) CompletionStage <U> (Other) CompletionStage <V> BiFunction(? super T, ? Super U, ? extends V) CompletionStage <T>
  • 17. How we leveraged the power of CompletableFuture • Use Case #1 (Remote Serivces) – Two remote services. – Both replicate service – We needed anyone to respond; faster! (acceptEither) – Lets simulate what we did! – Can be extended easily to any number of services! • public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
  • 18. How we leveraged the power of CompletableFuture - 2 • Use Case #2 (update UI after File FTP completes) – Application UI uploads file; not on UI thread; – UI thread is not blocked; it reacts whenever FTP is completed. – CompletableFuture<FTPStatus> ftp = CompletableFuture.supplyAsync(()->{ return FTPClient.uploadFile(file); }); ftp . whenComplete((ftpStatus,error)->{ //takes BiConsumer; alt. handle takes //BiFunction if (error == null){ //grab UI thread and update of successful FTP } else{ // grab UI thread and update of failure FTP } })
  • 19. Creating APIs to return CompletableFuture • How to expose CompletableFuture APIs for Clients! • Instantiate CompletableFuture • Set result to it asynchronously. public CompletableFuture<String> getPageContent(URL url){ CompletableFuture<String> futurePage = CompletableFuture<>(); Runnable task = ()->{ try{ String htmlContent = fetchPageContent(url); //long running futurePage.complete(htmlContent); //not with classicFuture // this is why it is CompletableFut. }catch(Throwable th){ futurePage.completeExceptionally(th); //set complete exceptionally } }; exec.submit(task); return futurePage; }
  • 20. Exception Handling • Exception Handling in CompletableFuture: – exceptionally() – handle() – whenComplete() • Time for Code  !
  • 21. ReentrantReadWriteLock Precursor to StampedLock • java.util.concurrent.locks.ReentrantReadWriteLock – Pessimistic Write – Pessimistic Read – No Optimistic Locking
  • 22. ReentrantReadWriteLock • ReentrantReadWriteLock Usage: private SomeClass theData; pri final ReadWriteLock myLocks = new ReentrantReadWriteLock(true); public void write(){ myLocks.writeLock().lock(); try{theData.write();} finally{myLocks.writeLock().unlock();} } public void read(){ myLocks.readLock().lock(); try{theData.read();} finally{myLocks.readLock().unlock();} }
  • 23. StampedLock • JDK8 addition into package java.util.concurrent.locks – Works with versions of StampedLock – the “Stamp” – Modes • Pessimistic Write • Pessimistic Read • Optimistic Read! (Optimization)
  • 24. Pessimistic StampedLocking Pessimistic Usage: private SomeClass theData; private final StampedLock lock= new StampedLock(true); public void write(){ long stamp = lock.writeLock(); try{theData.write();} finally{lock.writeLock(stamp);} } public void read(){ long stamp = lock.readLock(); try{theData.read();} finally{lock.unlockRead(stamp);} }
  • 25. Optimistic StampedLock Optimistic usage: • try OptimisticRead • Validate optimisticRead stamp • Based on the validation take further action. • Lets Try!!! private int p1, p2 StampedLock lock = new StampedLock(); public void read(){ long stamp = lock.tryOptimisticRead(); int l1 = p1; int l2 = p2; if(lock.validate(stamp)){ //validate the stamp (version) process(l1, l2); }else{ stamp = lock.readLock()//acquire pessimistic locks try{l1 = p1; l2= p2; process(l1, l2); } finally{lock.unlockRead(stamp)} } }
  • 26. Conclusion • CompletableFuture is powerful – Explore more – Write your own RxJava  • StampedLock is more efficient and optimized for particular use cases!