SlideShare a Scribd company logo
1 of 27
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!
Explore Java 8 concurrency abstractions like CompletableFuture and StampedLock

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 JavaYakov Fain
 
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 boxClaus Ibsen
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web ArtisansRaf 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 5Bukhori 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 DirectSencha
 
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 ClusterKonstantin Tsykulenko
 
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 5Soheil Khodayari
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon 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 TalkRed 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 meetupkrivachy
 
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 ProductionJoe Ferguson
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas 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

Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh 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
 
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
 
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 DevelopmentCodeOps 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 TalkCodeOps 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 DeliveryMurughan Palaniachari
 
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 Explore Java 8 concurrency abstractions like CompletableFuture and StampedLock

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 concurrencykshanth2101
 
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
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3JavaEE 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 PinterestPavan 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 FinagleGeoff Ballinger
 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013eamonnlong
 
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 MeetupAbel Muíño
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen Wang
 
EmberJS BucharestJS
EmberJS BucharestJSEmberJS BucharestJS
EmberJS BucharestJSRemus Rusanu
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus 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 reactorOrenEzer1
 

Similar to Explore Java 8 concurrency abstractions like CompletableFuture and StampedLock (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
 
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
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
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

(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 

Recently uploaded (20)

(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 

Explore Java 8 concurrency abstractions like CompletableFuture and StampedLock

  • 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!