SlideShare a Scribd company logo
8 - 24 minute delay
± 30 min. round trip
Web
• DNS
• Redirect
• Download HTML
• Download CSS + JS + Images
• Download more CSS + JS + Images
• ….
Ordering a pizza
• Several hours per page
• About 8 pages per order
Thread.setName(“Bob”);
String token =
getGitHubToken("https://github.com/login",<params>);
• Connect TCP
• Encryption handshake
• Push request data through socket
• … wait …
• Pull data from the socket
• Assemble and return the result
Blink of an eye
100ms
Time
Network latency: milliseconds
Application instruction: microseconds
Hardware instructions: nanoseconds
String token =
getGitHubToken("https://github.com/login",<params>);
=
#WRONG
Non Blocking For Everyone
with RxJava
@lyaruu
Frank Lyaruu
CTO Dexels
Non Blocking in Action 27
https://webtide.com/async-rest
So why are we still writing blocking code?
! It works pretty well in monoliths
! CPU and memory is cheap
! Networks are reliable and fast
! Writing non blocking code is hard
28
Writing non blocking code is rough
29
Servlet API
30
Non Blocking I/O Servlet API 3.1
31
A Blocking Echo Servlet 32
public class BlockingServlet extends HttpServlet {
private static final int BUFFER_SIZE = 1024;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int read = request.getInputStream().read(buffer, 0, BUFFER_SIZE);
if (read < 0)
break;
response.getOutputStream().write(buffer, 0, read);
}
}
}
A Non Blocking Echo Servlet 33
public class NonBlockingServlet extends HttpServlet {
private static final int BUFFER_SIZE = 1024;
@Override
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
AsyncContext asyncContext = request.startAsync(request, response);
asyncContext.setTimeout(0);
Echoer echoer = new Echoer(asyncContext);
request.getInputStream().setReadListener(echoer);
response.getOutputStream().setWriteListener(echoer);
}
private class Echoer implements ReadListener, WriteListener
{
private final byte[] buffer = new byte[BUFFER_SIZE];
private final AsyncContext asyncContext;
private final ServletInputStream input;
private final ServletOutputStream output;
private boolean complete;
private Echoer(AsyncContext asyncContext) throws IOException
{
this.asyncContext = asyncContext;
this.input = asyncContext.getRequest().getInputStream();
this.output = asyncContext.getResponse().getOutputStream();
}
@Override
public void onDataAvailable() throws IOException
{
while (input.isReady())
{
int read = input.read(buffer);
output.write(buffer, 0, read);
if (!output.isReady())
return;
}
if (input.isFinished())
{
complete = true;
asyncContext.complete();
}
}
@Override
public void onAllDataRead() throws IOException {}
@Override
public void onWritePossible() throws IOException
{
if (input.isFinished())
{
if (!complete)
asyncContext.complete();
}
else
{
onDataAvailable();
}
}
@Override
public void onError(Throwable failure)
{
failure.printStackTrace();
}
}
}
Maybe something simpler 34
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
AsyncContext asyncContext = request.startAsync(request, response);
final ServletOutputStream out = resp.getOutputStream();
final byte[] buf = new byte[1024];
final FileInputStream file = …;
out.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
while(out.isReady()) {
int len = file.read(buf);
if(len<0) {
return;
}
out.write(buf, 0, len);
}
}
});
}
35
Bob
36
Developer
Node.js 37
var server = http.createServer(function (req, res) {
req.pipe(res);
});
Node.js 38
var server = http.createServer(function (req, res) {
req.pipe(res);
});
A pipe… 39
Reactive Programming
40
Programming pipes
ReactiveX
41
Polyglot
RxJava RxScala RxJS RxPHP
Observable<T>
42
Will push zero or more items of type T
Followed by a ‘completed’ message
(or an error…)
RxJava Quick Intro 43
Observable.<String>just("Ouagadougou","Dakar","Accra","Rabat")
.subscribe(item->System.err.println(item));
Ouagadougou
Dakar
Accra
Rabat
RxJava Quick Intro 44
Observable.range(0, 1000)
.subscribe(item->System.err.println(item));
0
1
2
3
4
5
6
…
998
999
RxJava Quick Intro 45
Observable.range(0, 1000)
.skip(10)
.take(10)
.subscribe(item->System.err.println(item));
10
11
12
13
14
15
16
17
18
19
RxJava Quick Intro 46
Bytes.fromFile("citiesafrica.xml")
.lift(XML.parse())
.subscribe(item->System.err.println(item));
<cities>
<africa>
<city name="Lusaka"/>
<city name="Harare"/>
<city name="Kigali"/>
</africa>
</cities>
START_DOCUMENT
START_ELEMENT cities {}
START_ELEMENT africa {}
START_ELEMENT city {name=Lusaka}
END_ELEMENT city
START_ELEMENT city {name=Harare}
END_ELEMENT city
START_ELEMENT city {name=Kigali}
END_ELEMENT city
END_ELEMENT africa
END_ELEMENT cities
END_DOCUMENT
RxJava Quick Intro 47
Bytes.fromFile("citiesafrica.xml")
.lift(XML.parse())
.filter(e->e.getType()==XmlEventTypes.START_ELEMENT)
.map(e->e.getAttributes().get("name"))
.subscribe(item->System.err.println(item));
<cities>
<africa>
<city name="Lusaka"/>
<city name="Harare"/>
<city name="Kigali"/>
</africa>
</cities>
Lusaka
Harare
Kigali
static Observable<byte[]> createSourceObservable(HttpServletRequest req);
static Subscriber<byte[]> createSink(HttpServletResponse resp);
protected void doPost(HttpServletRequest req, final HttpServletResponse resp) {
createSourceObservable(req)
.subscribe(createSink(resp));
}
RxJava Quick Intro
Reactive API’s
49
A Blocking API
public static Double temperatureInCity(String city) {
return Double.parseDouble(HTTPClient
.get("http://api.weather.org/weather?q="+city)
.toXml()
.getContent("temperature"));
}
For consumers:
Double temperature = temperatureInCity("Tripoli");
Convert to Reactive
public Observable<Double> temperatureInCity(String city) {
return Observable.just(
Double.parseDouble(HTTPClient
.get("http://api.weather.org/weather?q="+city)
.toXml()
.getContent("temperature")
));
}
Sort of…
Double temp =
temperatureInCity(“Cairo”).blockingFirst();
updateTemperatureUI(temp);
This code is still just as blocking
But now the consumer and producer have independent
threading
Use a Non Blocking HTTP Client
public static Observable<Double> temperatureInCity(String city) {
return HTTP.get("http://api.weather.org/weather?q="+city)
.subscribeOn(Schedulers.io())
.lift(XML.parse())
.filter(e->e.getType()==XmlEventTypes.START_ELEMENT)
.filter(e->e.getText().equals("temperature"))
.first()
.map(xml->Double.parseDouble(xml.getAttributes().get("value")));
}
Add a Cache
public Observable<Double> temperatureInCity(String city) {
Double temperature = temperatureCache.get(city);
if(temperature!=null) {
return Observable.just(temperature);
}
return HTTP.get("http://api.weather.org/weather?q="+city)
.subscribeOn(Schedulers.io())
.lift(XML.parse())
.filter(e->e.getType()==XmlEventTypes.START_ELEMENT)
.filter(e->e.getText().equals("temperature"))
.first()
.map(xml->Double.parseDouble(xml.getAttributes().get("value")))
.doOnNext(temperature->temperatureCache.put(city,temperature));
}
Non Blocking Client
Blocking:
Double temp = temperatureInCity(“Cairo").toBlocking().first();
updateTemperatureUI(temp);
Non blocking:
temperatureInCity(“Nairobi”)
.observeOn(UISchedulers.uiThread())
.subscribe(d->updateTemperatureUI(d));
Challenges
57
Back pressure
58
Back pressure
59
Operation
A Blocking Echo Servlet 60
public class BlockingServlet extends HttpServlet {
private static final int BUFFER_SIZE = 1024;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int read = request.getInputStream().read(buffer, 0, BUFFER_SIZE);
if (read < 0)
break;
response.getOutputStream().write(buffer, 0, read);
}
}
}
Back pressure
61
! Observable: No back pressure
! Flowable: Back pressure
RxJava back pressure 62
Bytes.fromNetwork(“something_huge.xml”)
.lift(XML.parse())
.filter(e->e.getType()==XmlEventTypes.START_ELEMENT)
.map(e->e.getAttributes().get("name"))
.subscribe(item->doSomethingComplicated(item));
Back pressure
63
Operation
Back pressure
64
Operation
Memory Consumption
65
! Much better
! … or much worse
Error Handling
66
! Some patterns don’t work any more
! Requires some thought
Error handling 67
Servlet.handlePost()
.lift(XML.parse())
.subscribe(item->sendSomeWhere(item));
<cities>
<africa>
<city name="Lusaka"/>
<city name="Harare"/>
<city name="Kigali"/>
</cities>
START_DOCUMENT
START_ELEMENT cities {}
START_ELEMENT africa {}
START_ELEMENT city {name=Lusaka}
END_ELEMENT city
START_ELEMENT city {name=Harare}
END_ELEMENT city
START_ELEMENT city {name=Kigali}
END_ELEMENT city
END_ELEMENT africa
PARSE_ERROR
Non Blocking is not faster
68
! It is about utilising threads better
! If thread utilisation is not an issue, it
will perform similarly
Thoughts
69
! RxJava is lightweight and easy to add to existing
software
! Pleasant programming model
! Makes non blocking I/O bearable
! Can be used incrementally
Conclusions
70
! Threads are expensive
! Everything keeps getting faster except the speed of light
! Micro services
! Blocking code misbehaves under pressure
! The price of blocking communication will keep going up
I believe that, in time, some non blocking code is inevitable
Frank @Lyaruu dexels.com

Dexels frank@dexels.com
Please rate!

More Related Content

What's hot

Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
Tomasz Kowalczewski
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
Matt Stine
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
Tomasz Kowalczewski
 
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
Egor Andreevich
 
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
Dmitriy Dumanskiy
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
Dustin Graham
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
Thomas Roch
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
Savvycom Savvycom
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
Peter Lawrey
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
Fabio Collini
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
Eric Polerecky
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
Haim Yadid
 

What's hot (20)

Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
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
 
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 

Viewers also liked

Rx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com ObservablesRx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com Observables
lokimad
 
Real-world applications of the Reactive Extensions
Real-world applications of the Reactive ExtensionsReal-world applications of the Reactive Extensions
Real-world applications of the Reactive Extensions
Jonas Chapuis
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
Guillaume Valverde
 
Code Learn Share
Code Learn ShareCode Learn Share
Code Learn Share
Florina Muntenescu
 
A Journey Through MV Wonderland
A Journey Through MV WonderlandA Journey Through MV Wonderland
A Journey Through MV Wonderland
Florina Muntenescu
 
Thirty months of microservices. Stairway to heaven or highway to hell
Thirty months of microservices. Stairway to heaven or highway to hellThirty months of microservices. Stairway to heaven or highway to hell
Thirty months of microservices. Stairway to heaven or highway to hell
Sander Hoogendoorn
 
Aliyah: Looking for a hi-tech job in Israel
Aliyah: Looking for a hi-tech job in IsraelAliyah: Looking for a hi-tech job in Israel
Aliyah: Looking for a hi-tech job in Israel
Hayim Makabee
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
Welcome to rx java2
Welcome to rx java2Welcome to rx java2
Welcome to rx java2
Paresh Dudhat
 
Futures and Rx Observables: powerful abstractions for consuming web services ...
Futures and Rx Observables: powerful abstractions for consuming web services ...Futures and Rx Observables: powerful abstractions for consuming web services ...
Futures and Rx Observables: powerful abstractions for consuming web services ...
Chris Richardson
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mix
Florina Muntenescu
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
José Paumard
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
Shahar Barsheshet
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 

Viewers also liked (14)

Rx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com ObservablesRx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com Observables
 
Real-world applications of the Reactive Extensions
Real-world applications of the Reactive ExtensionsReal-world applications of the Reactive Extensions
Real-world applications of the Reactive Extensions
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Code Learn Share
Code Learn ShareCode Learn Share
Code Learn Share
 
A Journey Through MV Wonderland
A Journey Through MV WonderlandA Journey Through MV Wonderland
A Journey Through MV Wonderland
 
Thirty months of microservices. Stairway to heaven or highway to hell
Thirty months of microservices. Stairway to heaven or highway to hellThirty months of microservices. Stairway to heaven or highway to hell
Thirty months of microservices. Stairway to heaven or highway to hell
 
Aliyah: Looking for a hi-tech job in Israel
Aliyah: Looking for a hi-tech job in IsraelAliyah: Looking for a hi-tech job in Israel
Aliyah: Looking for a hi-tech job in Israel
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
 
Welcome to rx java2
Welcome to rx java2Welcome to rx java2
Welcome to rx java2
 
Futures and Rx Observables: powerful abstractions for consuming web services ...
Futures and Rx Observables: powerful abstractions for consuming web services ...Futures and Rx Observables: powerful abstractions for consuming web services ...
Futures and Rx Observables: powerful abstractions for consuming web services ...
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mix
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 

Similar to Non Blocking I/O for Everyone with RxJava

Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the networkMu Chun Wang
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
Yiguang Hu
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
Imre Nagi
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client servertrilestari08
 
Correcting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETCorrecting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NET
Brandon Minnick, MBA
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioRick Copeland
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
RTigger
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
Brandon Minnick, MBA
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
WindowsPhoneRocks
 
Correcting Common Async Await Mistakes in .NET
Correcting Common Async Await Mistakes in .NET Correcting Common Async Await Mistakes in .NET
Correcting Common Async Await Mistakes in .NET
Brandon Minnick, MBA
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
fadlihulopi
 

Similar to Non Blocking I/O for Everyone with RxJava (20)

Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 
Correcting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETCorrecting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NET
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
java sockets
 java sockets java sockets
java sockets
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
分散式系統
分散式系統分散式系統
分散式系統
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
Correcting Common Async Await Mistakes in .NET
Correcting Common Async Await Mistakes in .NET Correcting Common Async Await Mistakes in .NET
Correcting Common Async Await Mistakes in .NET
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 

More from Frank Lyaruu

Too young to quit, too old to change
Too young to quit, too old to changeToo young to quit, too old to change
Too young to quit, too old to change
Frank Lyaruu
 
Embracing Database Diversity with Kafka and Debezium
Embracing Database Diversity with Kafka and DebeziumEmbracing Database Diversity with Kafka and Debezium
Embracing Database Diversity with Kafka and Debezium
Frank Lyaruu
 
Scripting Languages in OSGi
Scripting Languages in OSGiScripting Languages in OSGi
Scripting Languages in OSGi
Frank Lyaruu
 
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
Frank Lyaruu
 
Developing Like There's No Tomorrow
Developing Like There's No TomorrowDeveloping Like There's No Tomorrow
Developing Like There's No Tomorrow
Frank Lyaruu
 
Service Discovery in OSGi: Beyond the JVM using Docker and Consul
Service Discovery in OSGi: Beyond the JVM using Docker and ConsulService Discovery in OSGi: Beyond the JVM using Docker and Consul
Service Discovery in OSGi: Beyond the JVM using Docker and Consul
Frank Lyaruu
 
Deploying OSGi on an Army of CubieTrucksSendrato powerpoint
Deploying OSGi on an Army of CubieTrucksSendrato powerpointDeploying OSGi on an Army of CubieTrucksSendrato powerpoint
Deploying OSGi on an Army of CubieTrucksSendrato powerpoint
Frank Lyaruu
 

More from Frank Lyaruu (7)

Too young to quit, too old to change
Too young to quit, too old to changeToo young to quit, too old to change
Too young to quit, too old to change
 
Embracing Database Diversity with Kafka and Debezium
Embracing Database Diversity with Kafka and DebeziumEmbracing Database Diversity with Kafka and Debezium
Embracing Database Diversity with Kafka and Debezium
 
Scripting Languages in OSGi
Scripting Languages in OSGiScripting Languages in OSGi
Scripting Languages in OSGi
 
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
ApacheCon Core: Service Discovery in OSGi: Beyond the JVM using Docker and Co...
 
Developing Like There's No Tomorrow
Developing Like There's No TomorrowDeveloping Like There's No Tomorrow
Developing Like There's No Tomorrow
 
Service Discovery in OSGi: Beyond the JVM using Docker and Consul
Service Discovery in OSGi: Beyond the JVM using Docker and ConsulService Discovery in OSGi: Beyond the JVM using Docker and Consul
Service Discovery in OSGi: Beyond the JVM using Docker and Consul
 
Deploying OSGi on an Army of CubieTrucksSendrato powerpoint
Deploying OSGi on an Army of CubieTrucksSendrato powerpointDeploying OSGi on an Army of CubieTrucksSendrato powerpoint
Deploying OSGi on an Army of CubieTrucksSendrato powerpoint
 

Recently uploaded

BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
ShahulHameed54211
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
Himani415946
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
TristanJasperRamos
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 

Recently uploaded (16)

BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 

Non Blocking I/O for Everyone with RxJava

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. 8 - 24 minute delay
  • 7. ± 30 min. round trip
  • 8. Web • DNS • Redirect • Download HTML • Download CSS + JS + Images • Download more CSS + JS + Images • ….
  • 9. Ordering a pizza • Several hours per page • About 8 pages per order
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 18. • Connect TCP • Encryption handshake • Push request data through socket • … wait … • Pull data from the socket • Assemble and return the result
  • 19.
  • 20. Blink of an eye 100ms
  • 21. Time Network latency: milliseconds Application instruction: microseconds Hardware instructions: nanoseconds
  • 23. =
  • 25.
  • 26. Non Blocking For Everyone with RxJava @lyaruu Frank Lyaruu CTO Dexels
  • 27. Non Blocking in Action 27 https://webtide.com/async-rest
  • 28. So why are we still writing blocking code? ! It works pretty well in monoliths ! CPU and memory is cheap ! Networks are reliable and fast ! Writing non blocking code is hard 28
  • 29. Writing non blocking code is rough 29
  • 31. Non Blocking I/O Servlet API 3.1 31
  • 32. A Blocking Echo Servlet 32 public class BlockingServlet extends HttpServlet { private static final int BUFFER_SIZE = 1024; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] buffer = new byte[BUFFER_SIZE]; while (true) { int read = request.getInputStream().read(buffer, 0, BUFFER_SIZE); if (read < 0) break; response.getOutputStream().write(buffer, 0, read); } } }
  • 33. A Non Blocking Echo Servlet 33 public class NonBlockingServlet extends HttpServlet { private static final int BUFFER_SIZE = 1024; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AsyncContext asyncContext = request.startAsync(request, response); asyncContext.setTimeout(0); Echoer echoer = new Echoer(asyncContext); request.getInputStream().setReadListener(echoer); response.getOutputStream().setWriteListener(echoer); } private class Echoer implements ReadListener, WriteListener { private final byte[] buffer = new byte[BUFFER_SIZE]; private final AsyncContext asyncContext; private final ServletInputStream input; private final ServletOutputStream output; private boolean complete; private Echoer(AsyncContext asyncContext) throws IOException { this.asyncContext = asyncContext; this.input = asyncContext.getRequest().getInputStream(); this.output = asyncContext.getResponse().getOutputStream(); } @Override public void onDataAvailable() throws IOException { while (input.isReady()) { int read = input.read(buffer); output.write(buffer, 0, read); if (!output.isReady()) return; } if (input.isFinished()) { complete = true; asyncContext.complete(); } } @Override public void onAllDataRead() throws IOException {} @Override public void onWritePossible() throws IOException { if (input.isFinished()) { if (!complete) asyncContext.complete(); } else { onDataAvailable(); } } @Override public void onError(Throwable failure) { failure.printStackTrace(); } } }
  • 34. Maybe something simpler 34 protected void doGet(HttpServletRequest req, HttpServletResponse resp) { AsyncContext asyncContext = request.startAsync(request, response); final ServletOutputStream out = resp.getOutputStream(); final byte[] buf = new byte[1024]; final FileInputStream file = …; out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { while(out.isReady()) { int len = file.read(buf); if(len<0) { return; } out.write(buf, 0, len); } } }); }
  • 37. Node.js 37 var server = http.createServer(function (req, res) { req.pipe(res); });
  • 38. Node.js 38 var server = http.createServer(function (req, res) { req.pipe(res); });
  • 42. Observable<T> 42 Will push zero or more items of type T Followed by a ‘completed’ message (or an error…)
  • 43. RxJava Quick Intro 43 Observable.<String>just("Ouagadougou","Dakar","Accra","Rabat") .subscribe(item->System.err.println(item)); Ouagadougou Dakar Accra Rabat
  • 44. RxJava Quick Intro 44 Observable.range(0, 1000) .subscribe(item->System.err.println(item)); 0 1 2 3 4 5 6 … 998 999
  • 45. RxJava Quick Intro 45 Observable.range(0, 1000) .skip(10) .take(10) .subscribe(item->System.err.println(item)); 10 11 12 13 14 15 16 17 18 19
  • 46. RxJava Quick Intro 46 Bytes.fromFile("citiesafrica.xml") .lift(XML.parse()) .subscribe(item->System.err.println(item)); <cities> <africa> <city name="Lusaka"/> <city name="Harare"/> <city name="Kigali"/> </africa> </cities> START_DOCUMENT START_ELEMENT cities {} START_ELEMENT africa {} START_ELEMENT city {name=Lusaka} END_ELEMENT city START_ELEMENT city {name=Harare} END_ELEMENT city START_ELEMENT city {name=Kigali} END_ELEMENT city END_ELEMENT africa END_ELEMENT cities END_DOCUMENT
  • 47. RxJava Quick Intro 47 Bytes.fromFile("citiesafrica.xml") .lift(XML.parse()) .filter(e->e.getType()==XmlEventTypes.START_ELEMENT) .map(e->e.getAttributes().get("name")) .subscribe(item->System.err.println(item)); <cities> <africa> <city name="Lusaka"/> <city name="Harare"/> <city name="Kigali"/> </africa> </cities> Lusaka Harare Kigali
  • 48. static Observable<byte[]> createSourceObservable(HttpServletRequest req); static Subscriber<byte[]> createSink(HttpServletResponse resp); protected void doPost(HttpServletRequest req, final HttpServletResponse resp) { createSourceObservable(req) .subscribe(createSink(resp)); } RxJava Quick Intro
  • 50. A Blocking API public static Double temperatureInCity(String city) { return Double.parseDouble(HTTPClient .get("http://api.weather.org/weather?q="+city) .toXml() .getContent("temperature")); } For consumers: Double temperature = temperatureInCity("Tripoli");
  • 51. Convert to Reactive public Observable<Double> temperatureInCity(String city) { return Observable.just( Double.parseDouble(HTTPClient .get("http://api.weather.org/weather?q="+city) .toXml() .getContent("temperature") )); }
  • 52.
  • 53. Sort of… Double temp = temperatureInCity(“Cairo”).blockingFirst(); updateTemperatureUI(temp); This code is still just as blocking But now the consumer and producer have independent threading
  • 54. Use a Non Blocking HTTP Client public static Observable<Double> temperatureInCity(String city) { return HTTP.get("http://api.weather.org/weather?q="+city) .subscribeOn(Schedulers.io()) .lift(XML.parse()) .filter(e->e.getType()==XmlEventTypes.START_ELEMENT) .filter(e->e.getText().equals("temperature")) .first() .map(xml->Double.parseDouble(xml.getAttributes().get("value"))); }
  • 55. Add a Cache public Observable<Double> temperatureInCity(String city) { Double temperature = temperatureCache.get(city); if(temperature!=null) { return Observable.just(temperature); } return HTTP.get("http://api.weather.org/weather?q="+city) .subscribeOn(Schedulers.io()) .lift(XML.parse()) .filter(e->e.getType()==XmlEventTypes.START_ELEMENT) .filter(e->e.getText().equals("temperature")) .first() .map(xml->Double.parseDouble(xml.getAttributes().get("value"))) .doOnNext(temperature->temperatureCache.put(city,temperature)); }
  • 56. Non Blocking Client Blocking: Double temp = temperatureInCity(“Cairo").toBlocking().first(); updateTemperatureUI(temp); Non blocking: temperatureInCity(“Nairobi”) .observeOn(UISchedulers.uiThread()) .subscribe(d->updateTemperatureUI(d));
  • 60. A Blocking Echo Servlet 60 public class BlockingServlet extends HttpServlet { private static final int BUFFER_SIZE = 1024; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] buffer = new byte[BUFFER_SIZE]; while (true) { int read = request.getInputStream().read(buffer, 0, BUFFER_SIZE); if (read < 0) break; response.getOutputStream().write(buffer, 0, read); } } }
  • 61. Back pressure 61 ! Observable: No back pressure ! Flowable: Back pressure
  • 62. RxJava back pressure 62 Bytes.fromNetwork(“something_huge.xml”) .lift(XML.parse()) .filter(e->e.getType()==XmlEventTypes.START_ELEMENT) .map(e->e.getAttributes().get("name")) .subscribe(item->doSomethingComplicated(item));
  • 65. Memory Consumption 65 ! Much better ! … or much worse
  • 66. Error Handling 66 ! Some patterns don’t work any more ! Requires some thought
  • 67. Error handling 67 Servlet.handlePost() .lift(XML.parse()) .subscribe(item->sendSomeWhere(item)); <cities> <africa> <city name="Lusaka"/> <city name="Harare"/> <city name="Kigali"/> </cities> START_DOCUMENT START_ELEMENT cities {} START_ELEMENT africa {} START_ELEMENT city {name=Lusaka} END_ELEMENT city START_ELEMENT city {name=Harare} END_ELEMENT city START_ELEMENT city {name=Kigali} END_ELEMENT city END_ELEMENT africa PARSE_ERROR
  • 68. Non Blocking is not faster 68 ! It is about utilising threads better ! If thread utilisation is not an issue, it will perform similarly
  • 69. Thoughts 69 ! RxJava is lightweight and easy to add to existing software ! Pleasant programming model ! Makes non blocking I/O bearable ! Can be used incrementally
  • 70. Conclusions 70 ! Threads are expensive ! Everything keeps getting faster except the speed of light ! Micro services ! Blocking code misbehaves under pressure ! The price of blocking communication will keep going up I believe that, in time, some non blocking code is inevitable
  • 71. Frank @Lyaruu dexels.com
 Dexels frank@dexels.com Please rate!