SlideShare uma empresa Scribd logo
1 de 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?

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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)
 

Semelhante a Asynchronous Programming with Java and JavaScript

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
 

Semelhante a Asynchronous Programming with Java and JavaScript (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
 

Último

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 

Último (20)

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 

Asynchronous Programming with Java and JavaScript

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