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
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));
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