SlideShare une entreprise Scribd logo
1  sur  34
S
Y
N
C
H
R
O
N
O
U
S
ASY
NC
HRO
NOUS
and
programming in
Łukasz Nawojczyk
contact@lukeahead.net
@LukeAheadNET
www.sproutigy.com
C10K
Handle more than 10.000 concurrent connections
What’s already in Java?
Multi-threading:
 Threads
 Future
 ExecutorService, ScheduledExecutorService, ForkJoinPool (Java 7+)
 BlockingQueue: ArrayBlockingQueue + LinkedBlockingQueue
 CopyOnWriteArrayList, ConcurrentHashMap
 ...
Non-blocking:
 NIO2 (Java 7+)
Where’s the problem
with async programming?
 HARD TO DESIGN
 HARD TO DEVELOP
 HARD TO HANDLE ERRORS
 HARD TO READ CODE
 HARD TO DEBUG
 HARD TO TEST
 HARD TO PROFILE
 HARD TO VISUALIZE
 HARD TO DOCUMENT
Open Source Community does not sleep
ParSeq
RxJavaVertX
Reactor
Guava
Akka
...and much more...
Futures
 Java Future (since Java 5)
 boolean isDone()
 V get()
 V get(long timeout,TimeUnit unit)
 cancel()
 Guava Listenable Future
 Guava Settable Future
 CompletableFuture (since Java 8)
[EXAMPLE CODE]
Why not Futures?
Java Futures are straight-forward to use for a single level of asynchronous
execution but they start to add non-trivial complexity when
they're nested (prior to Java 8 CompletableFuture).
Conditional asynchronous execution flows become difficult to optimally
compose (particularly as latencies of each request vary at runtime) using
Futures. It can be done of course, but it quickly becomes complicated (and thus
error prone) or prematurely blocks on 'Future.get()', eliminating the benefit of
asynchronous execution.
Source:
Ben Christensen http://techblog.netflix.com/2013/02/rxjava-netflix-api.html
Callbacks
Simple Theory:
Task A -> Task B -> Task C
Real Implementation:
TaskC = ...
TaskB = ...
TaskA = ...
TaskA.start(
TaskB.start(
TaskC.start()
)
) Pyramid of Doom
Callback (listener) example
indexRequestBuilder.execute(newActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
//TODO
}
@Override
public void onFailure(Throwable throwable) {
//TODO
}
});
Elasticsearch example
MIX Future+Callbacks in reality
Elasticsearch example – ListenableActionFuture
indexRequestBuilder.execute().
 boolean isDone()
 IndexResponse get()
 IndexResponse get(long timeout,TimeUnit unit)
 addListener(ActionListener<IndexResponse> listener)
Guava ListenableFuture is similar but has addCallback() instead
[EXAMPLE CODE]
Awaitility
await().atMost(5,
SECONDS).until(customerStatusIsUpdated());
https://github.com/jayway/awaitility
for testing asynchronous code
[EXAMPLE CODE]
What’s in JavaScript ?
 No multithreading, but can work asynchronously
 e.g. AJAX requests
 Asynchronous events are based callbacks
 jQuery provides promises & deferred (not good implementation)
 Standard interoperable Promise A+: https://promisesaplus.com/
 Multiple implementations
Promise
 listener for success event
 listener for failure event
 listener for done event (both success and failure)
 allows to specify next Promise (ability to build a chain of Promises)
! watch out for fluent chaining A.then(B).then(C)
it may be A->B->C or A->[B,C] depending on implementation
Implementations:
 JDeferred - https://github.com/jdeferred/jdeferred (based on jQuery)
 RxJava Promises - https://github.com/darylteo/rxjava-promises (based on Promise A+)
Promise + Deferred
Promise begin() {
Deffered deferred = ...
startAsync(
aresult -> {
if (aresult.failure()) deferred.failure();
else deferred.success();
}
);
return deferred.promise();
}
Promise promise = begin();
promise.done( ... );
promise.fail( ... );
promise.always( ... );
promise.then( doNext );
CLIENT
or use Java 8 CompletableFuture instead if you don’t like Deferred concept
[EXAMPLE CODE]
Reactor
“On a recent laptop with a dual-core processor,
it's possible to process over 15,000,000 events per second with the
RingBufferDispatcher and over 25,000,000 events per second in a single thread.”
reactor.on(Selectors.object("test"), new Consumer<Event<String>>() {
@Override
public void accept(Event<String> ev) {
log.info("Received event with data: " + ev.getData());
}
});
reactor.notify("test", Event.wrap("BLABLA"));
[EXAMPLE CODE]
ParSeq
 Parallelization of asynchronous operations (such as IO)
 Serialized execution for non-blocking computation
 Code reuse via task composition
 Simple error propagation and recovery
 Execution tracing and visualization
https://github.com/linkedin/parseq
ParSeq (2)
final Task<String> googleContentType = getContentType("http://www.google.com");
final Task<String> bingContentType = getContentType("http://www.bing.com");
final Task<String> contentTypes =
Task.par(googleContentType, bingContentType)
.map("concatenate", (google, bing) -> "Google: " + google + "n" + "Bing: " + bing + "n");
privateTask<String> getContentType(String url) {
return HttpClient.get(url).task()
.map("getContentType", response -> response.getContentType());
}
[EXAMPLE CODE]
RxJava
Observable<T>
Error Strategies:
 onErrorReturn
 onErrorResumeNext
Asynchronous Iterator
Event Iterable (pull) Subscription (push)
retrieve data T next() onNext(T)
discover error throws Exception onError(Exception)
complete returns onCompleted()
Asynchronous programming with observable streams
Akka
http://akka.io/
Actor Model
 multiple actors
 supervisors
Hello Librarian!
Have you read
“Java in 1 minute
for dummies“ ?
Yes, sure.
I’m too lazy to read it.
Could you summarize
this book for me?
No problem.
System.out.println(“Hello World”);
Now you know Java.
[EXAMPLE CODE]
Event-driven / Message-driven
WAIT FOR EVENT
HANDLE EVENT
EVENT QUEUE
EVENT LOOP
Vert.x
 Simple concurrency model. All code is single threaded, freeing from
the hassle of multi-threaded programming.
 Asynchronous programming model for writing truly scalable non-
blocking applications.
 Distributed event bus that spans the client and server side. The event
bus even penetrates into in-browser JavaScript allowing to create so-
called real-time web applications.
Vert.x simple HTTP server
VertxFactory.newVertx().createHttpServer().requestHandler(req -> {
if (req.path().equals("/test")) {
req.response().end("Hello World");
}
else {
String file = req.path().equals("/") ? "index.html" : req.path();
req.response().sendFile("webroot/" + file);
}
}).listen(8080);
[EXAMPLE CODE]
Copying streams
byte[] buf = new byte[4096];
while (true) {
int r = inputStream.read(buf);
if (r == -1) break;
outputStream.write(buf, 0, r);
}
Plain Old Java way Vert.x async way
Pump.createPump(input, output)
.start();
or
req.response()
.sendFile("webroot/" + file);
ALL IN JAVA CODE
processing every 4KB!
MOSTLY HANDLED BY JVM AND OS
no blocking threads
Apache Commons IOUtils.copy()
Guava ByteStreams.copy()
WARNING!
Using Event-loop
for long synchronous processing will lead to:
For long processing
use dedicated workers
outside main event-loop.
VERY SLOW QUEUE
Reactive Streams
http://ww.reactive-streams.org/
https://github.com/reactive-streams/reactive-streams-jvm/
 Akka
 Ratpack
 Reactive Rabbit
 Reactor
 RxJava
 Slick
 Vertx 3
public interface Publisher<T> {
public void subscribe(Subscriber<? superT> s);
}
public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
backpressure
handling
Reactive Manifesto
 Responsive: The system responds in a timely manner if at all possible. (...)
 Resilient: The system stays responsive in the face of failure. (...)
 Elastic/Scalable: The system stays responsive under varying workload. (...)
 Message Driven: (...) asynchronous message-passing to establish a boundary
between components that ensures loose coupling, isolation, location
transparency, and provides the means to delegate errors as messages. (...)
http://www.reactivemanifesto.org/
fail-fast / let it crash
Main targets
for asynchronous processing
 Network I/O
 Disk I/O
 Calling external APIs
Scaling
 Scale UP (vertical)
 adding more resources on single machine (CPU, memory, disk space...)
 Scale OUT (horizontal)
 adding more machines
 requires shared contract and serializable messages
Look for async-supporting libraries/frameworks that allows
not only vertical scaling but also helps with horizontal scaling.
Examples: Akka, Hazelcast, Vert.x, Atmosphere...
Hungry? Want even more?
 Atmosphere
 server - https://github.com/Atmosphere/atmosphere
 client - https://github.com/Atmosphere/wasync
 Ratpack - http://ratpack.io/
 LMAX Disruptor - https://lmax-exchange.github.io/disruptor/
 Hazelcast - http://hazelcast.com/
 Vert.x EventBus - http://vertx.io/core_manual_java.html#event-bus-api
 C10K & C10M
http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html
TO SUM UP...
Is asynchronous == multithreaded?
No! (not only)
Non-blocking I/O
Event Queue/Loop
Can we mix sync + async?
Sure!
SYNC or ASYNC
API
that supports
both sync and async
SYNC or ASYNC
caller (client) service
?
Enough talking
QUESTIONS?

Contenu connexe

Tendances

An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJavaSanjay Acharya
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Julian Robichaux
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Peter Antman
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
 
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
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmAlexey Fyodorov
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern JavaSimon Ritter
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 

Tendances (20)

An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
 
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
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithm
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Java after 8
Java after 8Java after 8
Java after 8
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern Java
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 

En vedette

Gestión Punto de Venta: programa asesoramiento
Gestión Punto de Venta: programa asesoramientoGestión Punto de Venta: programa asesoramiento
Gestión Punto de Venta: programa asesoramientoCarmen Llaneza
 
Витамины и другие химические вещества молока
Витамины и другие химические вещества молокаВитамины и другие химические вещества молока
Витамины и другие химические вещества молокаqwer78
 
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...Hacking Health Milano
 
zentron brief Ginserv
zentron brief Ginservzentron brief Ginserv
zentron brief GinservAmar .
 
Nos definimos por parejas.
Nos definimos por parejas.Nos definimos por parejas.
Nos definimos por parejas.albamacotera
 
الملصقات العلمية
الملصقات العلميةالملصقات العلمية
الملصقات العلميةresearchcenterm
 
עיצוב מצגת לתיאטרון
עיצוב מצגת לתיאטרוןעיצוב מצגת לתיאטרון
עיצוב מצגת לתיאטרוןSigal Mitgartz
 
Historia geológica y biológica del planeta tierra
Historia geológica y biológica del planeta tierraHistoria geológica y biológica del planeta tierra
Historia geológica y biológica del planeta tierracorindon
 

En vedette (14)

La historia
La historia La historia
La historia
 
FISICA Y QUIMICA
FISICA Y QUIMICAFISICA Y QUIMICA
FISICA Y QUIMICA
 
Gestión Punto de Venta: programa asesoramiento
Gestión Punto de Venta: programa asesoramientoGestión Punto de Venta: programa asesoramiento
Gestión Punto de Venta: programa asesoramiento
 
Витамины и другие химические вещества молока
Витамины и другие химические вещества молокаВитамины и другие химические вещества молока
Витамины и другие химические вещества молока
 
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...
Hacking Health Milano / Cafe#1: Obesità e adolescenza – con Itia/CNR e Proget...
 
Enseñar derechos humanos
Enseñar derechos humanosEnseñar derechos humanos
Enseñar derechos humanos
 
zentron brief Ginserv
zentron brief Ginservzentron brief Ginserv
zentron brief Ginserv
 
Nos definimos por parejas.
Nos definimos por parejas.Nos definimos por parejas.
Nos definimos por parejas.
 
الملصقات العلمية
الملصقات العلميةالملصقات العلمية
الملصقات العلمية
 
Government Supplier Magazine
Government Supplier MagazineGovernment Supplier Magazine
Government Supplier Magazine
 
עיצוב מצגת לתיאטרון
עיצוב מצגת לתיאטרוןעיצוב מצגת לתיאטרון
עיצוב מצגת לתיאטרון
 
Historia geológica y biológica del planeta tierra
Historia geológica y biológica del planeta tierraHistoria geológica y biológica del planeta tierra
Historia geológica y biológica del planeta tierra
 
Tesi alumno FUNIBER. Diana Carolina Szarawara - Formación de Profesores de es...
Tesi alumno FUNIBER. Diana Carolina Szarawara - Formación de Profesores de es...Tesi alumno FUNIBER. Diana Carolina Szarawara - Formación de Profesores de es...
Tesi alumno FUNIBER. Diana Carolina Szarawara - Formación de Profesores de es...
 
Ws3 safe system supporting vru (english version)
Ws3 safe system supporting vru (english version)Ws3 safe system supporting vru (english version)
Ws3 safe system supporting vru (english version)
 

Similaire à 4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy które można połączyć - Łukasz Nawojczyk

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Codemotion
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 referenceGiacomo Veneri
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)Yoshifumi Kawai
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018Trayan Iliev
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)Sharma Podila
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJeff Fox
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 

Similaire à 4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy które można połączyć - Łukasz Nawojczyk (20)

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
devday2012
devday2012devday2012
devday2012
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 reference
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery Deferred
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 

Dernier

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Dernier (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy które można połączyć - Łukasz Nawojczyk

  • 2. C10K Handle more than 10.000 concurrent connections
  • 3. What’s already in Java? Multi-threading:  Threads  Future  ExecutorService, ScheduledExecutorService, ForkJoinPool (Java 7+)  BlockingQueue: ArrayBlockingQueue + LinkedBlockingQueue  CopyOnWriteArrayList, ConcurrentHashMap  ... Non-blocking:  NIO2 (Java 7+)
  • 4. Where’s the problem with async programming?  HARD TO DESIGN  HARD TO DEVELOP  HARD TO HANDLE ERRORS  HARD TO READ CODE  HARD TO DEBUG  HARD TO TEST  HARD TO PROFILE  HARD TO VISUALIZE  HARD TO DOCUMENT
  • 5. Open Source Community does not sleep ParSeq RxJavaVertX Reactor Guava Akka ...and much more...
  • 6. Futures  Java Future (since Java 5)  boolean isDone()  V get()  V get(long timeout,TimeUnit unit)  cancel()  Guava Listenable Future  Guava Settable Future  CompletableFuture (since Java 8) [EXAMPLE CODE]
  • 7. Why not Futures? Java Futures are straight-forward to use for a single level of asynchronous execution but they start to add non-trivial complexity when they're nested (prior to Java 8 CompletableFuture). Conditional asynchronous execution flows become difficult to optimally compose (particularly as latencies of each request vary at runtime) using Futures. It can be done of course, but it quickly becomes complicated (and thus error prone) or prematurely blocks on 'Future.get()', eliminating the benefit of asynchronous execution. Source: Ben Christensen http://techblog.netflix.com/2013/02/rxjava-netflix-api.html
  • 8. Callbacks Simple Theory: Task A -> Task B -> Task C Real Implementation: TaskC = ... TaskB = ... TaskA = ... TaskA.start( TaskB.start( TaskC.start() ) ) Pyramid of Doom
  • 9. Callback (listener) example indexRequestBuilder.execute(newActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { //TODO } @Override public void onFailure(Throwable throwable) { //TODO } }); Elasticsearch example
  • 10. MIX Future+Callbacks in reality Elasticsearch example – ListenableActionFuture indexRequestBuilder.execute().  boolean isDone()  IndexResponse get()  IndexResponse get(long timeout,TimeUnit unit)  addListener(ActionListener<IndexResponse> listener) Guava ListenableFuture is similar but has addCallback() instead [EXAMPLE CODE]
  • 12. What’s in JavaScript ?  No multithreading, but can work asynchronously  e.g. AJAX requests  Asynchronous events are based callbacks  jQuery provides promises & deferred (not good implementation)  Standard interoperable Promise A+: https://promisesaplus.com/  Multiple implementations
  • 13. Promise  listener for success event  listener for failure event  listener for done event (both success and failure)  allows to specify next Promise (ability to build a chain of Promises) ! watch out for fluent chaining A.then(B).then(C) it may be A->B->C or A->[B,C] depending on implementation Implementations:  JDeferred - https://github.com/jdeferred/jdeferred (based on jQuery)  RxJava Promises - https://github.com/darylteo/rxjava-promises (based on Promise A+)
  • 14. Promise + Deferred Promise begin() { Deffered deferred = ... startAsync( aresult -> { if (aresult.failure()) deferred.failure(); else deferred.success(); } ); return deferred.promise(); } Promise promise = begin(); promise.done( ... ); promise.fail( ... ); promise.always( ... ); promise.then( doNext ); CLIENT or use Java 8 CompletableFuture instead if you don’t like Deferred concept [EXAMPLE CODE]
  • 15. Reactor “On a recent laptop with a dual-core processor, it's possible to process over 15,000,000 events per second with the RingBufferDispatcher and over 25,000,000 events per second in a single thread.” reactor.on(Selectors.object("test"), new Consumer<Event<String>>() { @Override public void accept(Event<String> ev) { log.info("Received event with data: " + ev.getData()); } }); reactor.notify("test", Event.wrap("BLABLA")); [EXAMPLE CODE]
  • 16. ParSeq  Parallelization of asynchronous operations (such as IO)  Serialized execution for non-blocking computation  Code reuse via task composition  Simple error propagation and recovery  Execution tracing and visualization https://github.com/linkedin/parseq
  • 17. ParSeq (2) final Task<String> googleContentType = getContentType("http://www.google.com"); final Task<String> bingContentType = getContentType("http://www.bing.com"); final Task<String> contentTypes = Task.par(googleContentType, bingContentType) .map("concatenate", (google, bing) -> "Google: " + google + "n" + "Bing: " + bing + "n"); privateTask<String> getContentType(String url) { return HttpClient.get(url).task() .map("getContentType", response -> response.getContentType()); } [EXAMPLE CODE]
  • 18. RxJava Observable<T> Error Strategies:  onErrorReturn  onErrorResumeNext Asynchronous Iterator Event Iterable (pull) Subscription (push) retrieve data T next() onNext(T) discover error throws Exception onError(Exception) complete returns onCompleted() Asynchronous programming with observable streams
  • 19. Akka http://akka.io/ Actor Model  multiple actors  supervisors Hello Librarian! Have you read “Java in 1 minute for dummies“ ? Yes, sure. I’m too lazy to read it. Could you summarize this book for me? No problem. System.out.println(“Hello World”); Now you know Java. [EXAMPLE CODE]
  • 20. Event-driven / Message-driven WAIT FOR EVENT HANDLE EVENT EVENT QUEUE EVENT LOOP
  • 21. Vert.x  Simple concurrency model. All code is single threaded, freeing from the hassle of multi-threaded programming.  Asynchronous programming model for writing truly scalable non- blocking applications.  Distributed event bus that spans the client and server side. The event bus even penetrates into in-browser JavaScript allowing to create so- called real-time web applications.
  • 22. Vert.x simple HTTP server VertxFactory.newVertx().createHttpServer().requestHandler(req -> { if (req.path().equals("/test")) { req.response().end("Hello World"); } else { String file = req.path().equals("/") ? "index.html" : req.path(); req.response().sendFile("webroot/" + file); } }).listen(8080); [EXAMPLE CODE]
  • 23. Copying streams byte[] buf = new byte[4096]; while (true) { int r = inputStream.read(buf); if (r == -1) break; outputStream.write(buf, 0, r); } Plain Old Java way Vert.x async way Pump.createPump(input, output) .start(); or req.response() .sendFile("webroot/" + file); ALL IN JAVA CODE processing every 4KB! MOSTLY HANDLED BY JVM AND OS no blocking threads Apache Commons IOUtils.copy() Guava ByteStreams.copy()
  • 24. WARNING! Using Event-loop for long synchronous processing will lead to: For long processing use dedicated workers outside main event-loop. VERY SLOW QUEUE
  • 25. Reactive Streams http://ww.reactive-streams.org/ https://github.com/reactive-streams/reactive-streams-jvm/  Akka  Ratpack  Reactive Rabbit  Reactor  RxJava  Slick  Vertx 3 public interface Publisher<T> { public void subscribe(Subscriber<? superT> s); } public interface Subscriber<T> { public void onSubscribe(Subscription s); public void onNext(T t); public void onError(Throwable t); public void onComplete(); } public interface Subscription { public void request(long n); public void cancel(); } backpressure handling
  • 26. Reactive Manifesto  Responsive: The system responds in a timely manner if at all possible. (...)  Resilient: The system stays responsive in the face of failure. (...)  Elastic/Scalable: The system stays responsive under varying workload. (...)  Message Driven: (...) asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation, location transparency, and provides the means to delegate errors as messages. (...) http://www.reactivemanifesto.org/
  • 27. fail-fast / let it crash
  • 28. Main targets for asynchronous processing  Network I/O  Disk I/O  Calling external APIs
  • 29. Scaling  Scale UP (vertical)  adding more resources on single machine (CPU, memory, disk space...)  Scale OUT (horizontal)  adding more machines  requires shared contract and serializable messages Look for async-supporting libraries/frameworks that allows not only vertical scaling but also helps with horizontal scaling. Examples: Akka, Hazelcast, Vert.x, Atmosphere...
  • 30. Hungry? Want even more?  Atmosphere  server - https://github.com/Atmosphere/atmosphere  client - https://github.com/Atmosphere/wasync  Ratpack - http://ratpack.io/  LMAX Disruptor - https://lmax-exchange.github.io/disruptor/  Hazelcast - http://hazelcast.com/  Vert.x EventBus - http://vertx.io/core_manual_java.html#event-bus-api  C10K & C10M http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html
  • 32. Is asynchronous == multithreaded? No! (not only) Non-blocking I/O Event Queue/Loop
  • 33. Can we mix sync + async? Sure! SYNC or ASYNC API that supports both sync and async SYNC or ASYNC caller (client) service ?