SlideShare una empresa de Scribd logo
1 de 71
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 

La actualidad más candente (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
 

Destacado

Destacado (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 a Non Blocking I/O for Everyone with RxJava

Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
Mu Chun Wang
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
trilestari08
 
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
Rick Copeland
 

Similar a 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
 

Más de Frank Lyaruu

Más de 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
 

Último

Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
ellan12
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
sexy call girls service in goa
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 

Último (20)

How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 

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!