SlideShare a Scribd company logo
1 of 80
The Road to Reactive with
RxJava
Or: How to use non blocking I/O without wanting to kill yourself
Legacy
“An accomplishment that remains relevant long after a person has died”
Software is not so lucky
Why don’t we love old code?
This comparison isn’t fair
Get to the point, please?
Throwing away old code is
so tempting…
Replacing legacy systems is really
hard
Love your code like your home town
</rant>
Frank Lyaruu
CTO at Dexels, building enterprise software for sports federations.
Sportlink 2003
Sportlink 2016
Blocking code
A servlet story
Blocking code
String response = callMethod();
doSomethingElse(response);
Blocking code
• Easy to compose using the ‘;’ operator ;-)
• Easy to reason about
• Pleasant to debug
• Maps nicely to low level instructions
• It’s efficient*
• It’s extremely mature
• It’s familiar
Blocking code looks pretty good
Why mess with it?
Blocking code
• It’s only efficient when it is doing something
• Not when it is waiting for something
• At scale, threads are expensive
Example: Remote Procedure
Calls
public Result getSomeRemoteData(String argument) {
return HttpClient.callRemoteURL(argument);
}
See: https://webtide.com/async-rest/
Microservices
• Remote calls to other parts of the application are everywhere
• A remote call might be calling another remote call
• One operation might be blocking more than one thread
Blocking code: Stability
• Slow network connections are very expensive
• Performance problems cause an explosion of threads….
• … which cause performance problems
• Blocking systems don’t degrade gracefully
Blocking code
• Expensive at scale
• A liability for distributed systems
Non blocking code
A non-blocking method will return before it is truly ‘finished’
So when it returns without an error, that means nothing
Non blocking code
• When is it finished?
• How do I know if it succeeded?
• If it did, where is my result?
• How often can I call it again?
Callbacks
public void performAsyncMethod(String argument, Callback callback);
performAsyncMethod("arg", result->{… do stuff …});
Callbacks
public void executeAsync() {
performAsyncMethod("arg", result->
performOperation(result, r->
performAnotherOperation(r, res->{})
)
);
}
Servlet 3.1 Non-blocking I/O
A blocking Echo Servlet
public class BlockingServlet extends HttpServlet {
private static final int BUFFER_SIZE = 1024;
protected void service(HttpServletRequest request, HttpServletResponse response){
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
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();
}
}
}
A simpler example
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);
}
}
});
}
Blocking code & I/O
don’t play nice
Why?
Threads don’t react, they DO
I/O is reactive by nature
Node.js
var server = http.createServer(function (req, res) {
req.pipe(res);
});
Reactive Programming
“Programming pipes”
ReactiveX
Polyglot API for reactive streams
RxJava RxJS rx.Net … RxPHP RxSwift
Source: Observable
Destination: Subscriber
The world view of RxJava
RxJava at High speed
Observable.<String>just("Ouagadougou","Dakar","Accra","Rabat")
.subscribe(System.err::println);
Ouagadougou
Dakar
Accra
Rabat
RxJava at High speed
Observable.range(0, 1000)
.subscribe(System.err::println);
0
1
2
3
4
5
6
…
998
999
RxJava at High speed
Observable.range(0, 1000)
.skip(10)
.take(10)
.subscribe(System.err::println);
10
11
12
13
14
15
16
17
18
19
RxJava at High speed
Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.subscribe(System.err::println);
0 (with one second delay each)
1
2
3
4
RxJava at High speed
Bytes.fromClassPath("citiesafrica.xml")
.lift(XML.parse())
.subscribe(System.err::println);
<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
XML parsing example: https://github.com/flyaruu/xml-rx
RxJava at High speed
Bytes.fromClassPath("citiesafrica.xml")
.lift(XML.parse())
.filter(e->e.getType()==XmlEventTypes.START_ELEMENT)
.map(e->e.getAttributes().get("name"))
.subscribe(System.err::println);
<cities>
<africa>
<city name="Lusaka"/>
<city name="Harare"/>
<city name="Kigali"/>
</africa>
</cities>
Lusaka
Harare
Kigali
RxJava at High speed
Database.from(“jdbc:…”)
.select("select name from cities where continent = ? order by name")
.parameter("africa")
.getAs(String.class)
.subscribe(System.err::println);
Harare
Lusaka
Kigali
Non Blocking Servlets
static Observable<byte[]> createReadListener(HttpServletRequest req);
static Subscriber<byte[]> createOutput(HttpServletRequest req);
protected void doPost(HttpServletRequest req, final HttpServletResponse resp) {
createReadListener(req)
.subscribe(createOutput(req));
}
Non Blocking Servlets
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection(“test”);
collection
.find()
.writeAsJSON()
.subscribe(createOutput(req));
}
Non Blocking Servlets
protected void doPost(HttpServletRequest req, final HttpServletResponse resp) {
String requestEncoding = (String) req.getHeader("Content-Encoding");
Observable<byte[]> in =
createReadListener(req)
.lift(NavajoStreamOperators.decompress(requestEncoding))
.lift(XML.parse())
.lift(DomBuilder.parse())
.lift(...)
.subscribe(createOutput(req));
}
Observable API’s
Connecting hoses
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");
Create Observable APIs
public Observable<Double> temperatureInCity(String city) {
return Observable.just(
Double.parseDouble(HTTPClient
.get("http://api.weather.org/weather?q="+city)
.toXml()
.getContent("temperature")
));
}
Well…
Double temp = temperatureInCity(“Cairo").toBlocking().first();
updateTemperatureUI(temp);
This code is still just as blocking
But now the consumer and producer are independent of threading
The API provider and consumer
choose their own 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")));
}
And the consumer notices nothing…
Non blocking consumer
Blocking:
Double temp = temperatureInCity(“Cairo").toBlocking().first();
updateTemperatureUI(temp);
Non blocking:
temperatureInCity(“Nairobi”)
.observeOn(UISchedulers.uiThread())
.subscribe(d->updateTemperatureUI(d));
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")));
}
It’s just a library
• Not a new language
• Not a new framework
• Can be implemented incrementally
• Only needs a recent Java version and a recent Servlet Engine (if you
use servlets)
Limitations
Non blocking is not faster
• Non blocking is about utilising threads better
• If thread utilisation is not a issue, it will perform about the same
Backpressure
Isn’t easy
Memory consumption
• Might be much better
• … or much worse
Things I skipped:
• Error handling
• Scheduling
• ByteBuffers and Bufferpools
• A lot of fancy operators
Conclusions
Thank you!

More Related Content

What's hot

Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programmingEric Polerecky
 
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
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
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 CompletableFuturesHaim Yadid
 
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 jsThomas Roch
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerIslam Sharabash
 
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
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
CLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsCLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsForrest Norvell
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptLeonardo Borges
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaFabio Collini
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 

What's hot (20)

Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
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
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
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
 
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
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
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
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
CLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsCLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.js
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
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
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 

Similar to The Road to Reactive Programming with RxJava</TITLE

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
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
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
 
Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Metosin Oy
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyErsin Er
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxpetabridge
 

Similar to The Road to Reactive Programming with RxJava</TITLE (20)

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
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
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
 
Reitit - Clojure/North 2019
Reitit - Clojure/North 2019Reitit - Clojure/North 2019
Reitit - Clojure/North 2019
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Node.js
Node.jsNode.js
Node.js
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 

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 changeFrank 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 DebeziumFrank Lyaruu
 
Scripting Languages in OSGi
Scripting Languages in OSGiScripting Languages in OSGi
Scripting Languages in OSGiFrank 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 TomorrowFrank 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 ConsulFrank 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 powerpointFrank 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

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

The Road to Reactive Programming with RxJava</TITLE

  • 1. The Road to Reactive with RxJava Or: How to use non blocking I/O without wanting to kill yourself
  • 2. Legacy “An accomplishment that remains relevant long after a person has died”
  • 3.
  • 4.
  • 5. Software is not so lucky
  • 6.
  • 7.
  • 8.
  • 9. Why don’t we love old code?
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19. Get to the point, please?
  • 20. Throwing away old code is so tempting…
  • 21.
  • 22. Replacing legacy systems is really hard
  • 23. Love your code like your home town </rant>
  • 24. Frank Lyaruu CTO at Dexels, building enterprise software for sports federations.
  • 28. Blocking code String response = callMethod(); doSomethingElse(response);
  • 29.
  • 30. Blocking code • Easy to compose using the ‘;’ operator ;-) • Easy to reason about • Pleasant to debug • Maps nicely to low level instructions • It’s efficient* • It’s extremely mature • It’s familiar
  • 31. Blocking code looks pretty good Why mess with it?
  • 32. Blocking code • It’s only efficient when it is doing something • Not when it is waiting for something • At scale, threads are expensive
  • 33. Example: Remote Procedure Calls public Result getSomeRemoteData(String argument) { return HttpClient.callRemoteURL(argument); }
  • 35. Microservices • Remote calls to other parts of the application are everywhere • A remote call might be calling another remote call • One operation might be blocking more than one thread
  • 36. Blocking code: Stability • Slow network connections are very expensive • Performance problems cause an explosion of threads…. • … which cause performance problems • Blocking systems don’t degrade gracefully
  • 37. Blocking code • Expensive at scale • A liability for distributed systems
  • 38. Non blocking code A non-blocking method will return before it is truly ‘finished’ So when it returns without an error, that means nothing
  • 39. Non blocking code • When is it finished? • How do I know if it succeeded? • If it did, where is my result? • How often can I call it again?
  • 40. Callbacks public void performAsyncMethod(String argument, Callback callback); performAsyncMethod("arg", result->{… do stuff …});
  • 41. Callbacks public void executeAsync() { performAsyncMethod("arg", result-> performOperation(result, r-> performAnotherOperation(r, res->{}) ) ); }
  • 43. A blocking Echo Servlet public class BlockingServlet extends HttpServlet { private static final int BUFFER_SIZE = 1024; protected void service(HttpServletRequest request, HttpServletResponse response){ 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); } } }
  • 44. A non blocking Echo Servlet 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(); } } }
  • 45. A simpler example 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); } } }); }
  • 46.
  • 47. Blocking code & I/O don’t play nice
  • 48. Why? Threads don’t react, they DO I/O is reactive by nature
  • 49. Node.js var server = http.createServer(function (req, res) { req.pipe(res); });
  • 50.
  • 52. ReactiveX Polyglot API for reactive streams RxJava RxJS rx.Net … RxPHP RxSwift
  • 54. RxJava at High speed Observable.<String>just("Ouagadougou","Dakar","Accra","Rabat") .subscribe(System.err::println); Ouagadougou Dakar Accra Rabat
  • 55. RxJava at High speed Observable.range(0, 1000) .subscribe(System.err::println); 0 1 2 3 4 5 6 … 998 999
  • 56. RxJava at High speed Observable.range(0, 1000) .skip(10) .take(10) .subscribe(System.err::println); 10 11 12 13 14 15 16 17 18 19
  • 57. RxJava at High speed Observable.interval(1, TimeUnit.SECONDS) .take(5) .subscribe(System.err::println); 0 (with one second delay each) 1 2 3 4
  • 58. RxJava at High speed Bytes.fromClassPath("citiesafrica.xml") .lift(XML.parse()) .subscribe(System.err::println); <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 XML parsing example: https://github.com/flyaruu/xml-rx
  • 59. RxJava at High speed Bytes.fromClassPath("citiesafrica.xml") .lift(XML.parse()) .filter(e->e.getType()==XmlEventTypes.START_ELEMENT) .map(e->e.getAttributes().get("name")) .subscribe(System.err::println); <cities> <africa> <city name="Lusaka"/> <city name="Harare"/> <city name="Kigali"/> </africa> </cities> Lusaka Harare Kigali
  • 60. RxJava at High speed Database.from(“jdbc:…”) .select("select name from cities where continent = ? order by name") .parameter("africa") .getAs(String.class) .subscribe(System.err::println); Harare Lusaka Kigali
  • 61. Non Blocking Servlets static Observable<byte[]> createReadListener(HttpServletRequest req); static Subscriber<byte[]> createOutput(HttpServletRequest req); protected void doPost(HttpServletRequest req, final HttpServletResponse resp) { createReadListener(req) .subscribe(createOutput(req)); }
  • 62. Non Blocking Servlets protected void doGet(HttpServletRequest req, final HttpServletResponse resp) { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> collection = database.getCollection(“test”); collection .find() .writeAsJSON() .subscribe(createOutput(req)); }
  • 63. Non Blocking Servlets protected void doPost(HttpServletRequest req, final HttpServletResponse resp) { String requestEncoding = (String) req.getHeader("Content-Encoding"); Observable<byte[]> in = createReadListener(req) .lift(NavajoStreamOperators.decompress(requestEncoding)) .lift(XML.parse()) .lift(DomBuilder.parse()) .lift(...) .subscribe(createOutput(req)); }
  • 65. 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");
  • 66. Create Observable APIs public Observable<Double> temperatureInCity(String city) { return Observable.just( Double.parseDouble(HTTPClient .get("http://api.weather.org/weather?q="+city) .toXml() .getContent("temperature") )); }
  • 67.
  • 68. Well… Double temp = temperatureInCity(“Cairo").toBlocking().first(); updateTemperatureUI(temp); This code is still just as blocking But now the consumer and producer are independent of threading
  • 69. The API provider and consumer choose their own threading
  • 70. 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"))); } And the consumer notices nothing…
  • 71. Non blocking consumer Blocking: Double temp = temperatureInCity(“Cairo").toBlocking().first(); updateTemperatureUI(temp); Non blocking: temperatureInCity(“Nairobi”) .observeOn(UISchedulers.uiThread()) .subscribe(d->updateTemperatureUI(d));
  • 72. 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"))); }
  • 73. It’s just a library • Not a new language • Not a new framework • Can be implemented incrementally • Only needs a recent Java version and a recent Servlet Engine (if you use servlets)
  • 75. Non blocking is not faster • Non blocking is about utilising threads better • If thread utilisation is not a issue, it will perform about the same
  • 77. Memory consumption • Might be much better • … or much worse
  • 78. Things I skipped: • Error handling • Scheduling • ByteBuffers and Bufferpools • A lot of fancy operators

Editor's Notes

  1. - History is pretty hard on software
  2. There are obvious examples of ‘Legacy’ in Art and Music
  3. If we get a little bit closer to more technical subjects Nobody would say: “We have better cars now” Nobody complains that it does not have air conditioning. Nobody will say: “I have a 2016 Ford Fiesta and that one is better in (nearly) every way”
  4. It does not get the same kind of respect Why is ‘legacy’ the most dreaded word for developers? Why don’t we have similar feelings about ‘classic’ pieces of software?
  5. This one just hurts
  6. This is just sentimental Retrogaming
  7. - Why are the Sputnik and the Apollo admired in museums, but the software that ran on the 32k computer that got it to their destinations is nowhere to be found
  8. Classics don’t need to change, I would not expect Mozart to develop a beat, or my car to turn hybrid at some point. We do expect this from software:
  9. Disrepair Soggy People who could leave, left
  10. Late sixties, early seventies, the local government decided that this neighbourhood could not be saved. Plan to tear it down completely and to rebuild it. Huge amount of protest, people refused to leave.
  11. Now it is a very pleasant place to be. Varied, 400 years of different building. Buildings got renovated.
  12. Fast forward a few decades: One of the most desired area’s in the country. It is nice. It has soul. And I think we dodged a bullet there, because the buildings of the 70ties were horrible
  13. Really boring at best
  14. And a ghetto at worst (the hole in the building is unrelated)
  15. Starting clean! You throw away all your old todo’s / tests / documentation All the technical debt All the not-so-great design decisions You can fantasise about how all problems are gone once you use all the shiny new technologies New technologies prey on this: Rails, Ratpack: Look how easy it is to make something new
  16. 7:30
  17. Large (old) systems are very difficult to replace / and in the not satisfying If not careful, we’ll get very similar problems again We massively underestimate the effort of rebuilding. Rebuilding large projects are the most doomed projects ever. Usually 90% is easy. We need to get over it. We will live in a world of old software We better start getting good at this. And keep this in mind when we write new software
  18. With all its imperfections Fix what is broken Replace what is no longer relevant … but don’t fall into the ‘better rebuild’ trap We’re adults now. We should take long term responsibility for what we make. Banks still run Cobol. Code has a way of sticking around
  19. I have worked on one application for 13 years
  20. Oracle database Java Servlet backend Swing Client
  21. 12:00 I’ve worked 13 years on this, and it has not been boring Freek the app builder More interesting and creative than building new green field applications all the time. I’ve learned to face my demons of the past
  22. So common it is invisible
  23. One way or another, after the method is terminated, it is done.
  24. Also performance tuning Since my trusty C64 thirty years ago
  25. In many cases, the right answer might be: Don’t mess with it
  26. Threads eat quite a bit of memory and cpu, even when blocked
  27. Could be a RMI / god forbid SOAP thing or a REST/HTTP call HTTP maps nicely to the ‘method’ or ‘procedure’ model Creates connection Pushes the request data through the socket Waits for socket data to come in Reassembles the response Even a tiny 1ms delay is an eternity for a modern cpu Having 95% waiting threads is not uncommon
  28. There is a penalty to async / non blocking code, but it is dwarfed by the I/O times
  29. A multi-machine stack trace, and it consumes a thread on every machine
  30. Logging war story? Slow network connections => MOBILE Bulkheading for performance problems does not work
  31. Distributed = all systems (Or microservices) So if we want microservices at scale, at some point we’ll need to face non-blocking communication
  32. 22min Example write to a socket In blocking code, doing a write will mean it completed successfully
  33. This is how callbacks compose Pyramid of doom Life has gotten a whole lot harder Composition with ‘;’ no longer works This is going to be painful
  34. Ask about Servlets Since 2012
  35. For non-blocking code (and smart people have spent a lot of time on this. Once you actually start to do something, it gets much worse >100 lines and very complicated
  36. I know I shouldn’t mention Node here, but this is MUCH BETTER This is how you talk about data But how can we get closer to this?
  37. A hose You won’t describe a pipe like ‘Take one drop, transport, etc. How fast should I move the water? - What if there is no more water? What if the flow increases? Decreases? It does not need to contain all the water This is what node does A pipe is declarative
  38. Not very scientific Declarative, about dealing with stuff that happens 32 min
  39. Poll. Use it? Went to talks?
  40. Observable will emit 0 or more data items, and then call complete. Or an error and be silent forever Very quick examples
  41. Like a pushing list Similar to Java 8 streams, but supports push
  42. You can chain operators Even though it says 1000, it will never do more than 20 in this case
  43. You can chain operators Can not be done by Java Streams
  44. Explain byte source Github
  45. You can chain operators
  46. JDBC is a blocking API
  47. We’ve got our Node.js ‘pipe’ I’m not going to show you the gnarly glue code Especially with mobile clients, even if I do any actual logic in a blocking style, this can save a ton. This is an immediate improvement
  48. *slightly simplified
  49. Ideally, you write all your code non blocking Chances are, that you have blocking code lying around. 40m
  50. This will do its thing, but for one of the reasons we’ve talked about before, we’d like to make this non-blocking. Where to begin? 41m
  51. Behaves pretty much the same. A little bit of overhead.
  52. You can’t bolt on non-blocking behaviour It behaves exactly the same: Single threaded. And that is HUGE
  53. So now the API provider is no longer blocking a thread during the HTTP call (but the consumer still might) The ‘first’ will unsubscribe and cancel the connection
  54. The big payoff: If both ends of the API are non blocking, it frees up a thread for its duration. 45m
  55. The threading model changes with the data
  56. The API’s might be clunky but they are well defined and performant Observable API’s can future proof your application Suitable for guerilla / grassroots adoption -> req. your CTO Many technologies focus on green field applications
  57. It’s not all rainbows and unicorns
  58. Performance will only improve when threads are expensive
  59. Incremental updates are the way to go, even for profound changes like non blocking code Your software will be around longer than you think Big rebuilds are expensive and fail often RxJava can improve performance, and open up a whole new type of programming, without much risk
  60. 52