SlideShare a Scribd company logo
TOMASZ KOWALCZEWSKI
REACTIVE JAVA
 Reactive view of the world
 Desgining interface for reactive interactions (the cat experiment)
 Rx Java as implementation of that interface
 Lessons learned
STUFF I WILL TALK ABOUT
REACTIVE
“readily responsive to a stimulus”
Merriam-Webster dictionary
SYNCHRONOUS PULL COMMUNICATION
Client Server
Request
Response
Server processing
Network latency
OBSERVABLE ->
OBSERVER ->
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
boolean alive();
}
public interface ShrödingersCat {
Future<Boolean> alive();
}
public interface ShrödingersCat {
Iterator<Boolean> alive();
}
SUBCRIPTIONS AND EVENTS
t
subscribe
onNext*
onCompleted | onError
PULL VS PUSH
Observer Observable
Subscribe
...
onNext
Server processing
Network latency
Maybe this one needs all the data...
RX JAVA BY NETFLIX
 Open source project with Apache License.
 Java implementation of Rx Observables from Microsoft
 The Netflix API uses it to make the entire service layer asynchronous
 Provides a DSL for creating computation flows out of asynchronous sources
using collection of operators for filtering, selecting, transforming and
combining that flows in a lazy manner
 These flows are called Observables – collection of events with push
semantics (as oposed to pull in Iterator)
 Targets the JVM not a language. Currently supports Java, Groovy, Clojure,
and Scala
OBSERVABLE
public interface ShrödingersCat {
Observable<Boolean> alive();
}
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
Observable<Boolean> alive();
}
cat
.alive()
.subscribe(status -> System.out.println(status));
public interface ShrödingersCat {
Observable<Boolean> alive();
}
cat
.alive()
.throttleWithTimeout(250, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
.filter(isAlive -> isAlive)
.map(Boolean::toString)
.subscribe(status -> display.display(status));
SERVICE RETURNING OBSERVABLE
 Maybe it executes its logic on subscriber thread?
 Maybe it delegates part of the work to other threads?
 Does it use NIO?
 Maybe its an actor?
 Does it return cached data?
 Observer does not care!
HOW IS THE OBSERVABLE IMPLEMENTED?
MARBLE DIAGRAMS
MAP(FUNC1)
MERGE(OBSERVABLE...)
CONCAT(OBSERVABLE...)
FLATMAP(FUNC)
Observable<ShrödingersCat> cats = listAllCats();
cats
.flatMap(cat ->
Observable
.from(catService.getPicturesFor(cat))
.filter(image -> image.size() < 100 * 1000)
)
).subscribe();
FLATMAP(FUNC)
CACHE
Random random = new Random();
Observable<Integer> observable = Observable
.range(1, 100)
.map(random::nextInt)
.cache();
observable.subscribe(System.out::println);
observable.subscribe(System.out::println);
...
 Always prints same values
INJECTING CUSTOM OPERATORS USING LIFT
class InternStrings implements Observable.Operator<String, String> {
public Subscriber<String> call(Subscriber<String> subscriber) {
return new Subscriber<String>() {
public void onCompleted() { subscriber.onCompleted(); }
public void onError(Throwable e) { subscriber.onError(e); }
public void onNext(String s) {
subscriber.onNext(s.intern()); };
}
}
Observable.from("AB", "CD", "AB", "DE")
.lift(new InternStrings())
.subscribe();
 Valuable for instrumentation
 Inject debug code – see rxjava-contrib/rxjava-debug
 Inject performance counters
ERROR HANDLING
 Correctly implemented observable will not produce any events after
error notification
 Operators available for fixing observables not adhering to this rule
 Pass custom error handling function to subscribe
 Transparently substite failing observable with another one
 Convert error into regular event
 Retry subscription in hope this time it will work...
ESCAPING THE MONAD
Iterable<String> strings = Observable.from(1, 2, 3, 4)
.map(i -> Integer.toString(i))
.toBlockingObservable()
.toIterable();
// or (and many more)
T firstOrDefault(T defaultValue, Func1 predicate)
Iterator<T> getIterator()
Iterable<T> next()
 Inverses the dependency, will wait for next item, then execute
 Usually to interact with other, synchronous APIs
 While migrating to reactive approach in small increments
 To trigger early evaluation while debugging
OBSERVER
public interface Observer<T> {
void onCompleted();
void onError(Throwable e);
void onNext(T args);
}
CREATING OBSERVABLES
Observable<Boolean> watchTheCat =
Observable.create(observer -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
});
 create accepts OnSubscribe function
 Executed for every subscriber upon subscription
 This example is not asynchronous
CREATING OBSERVABLES
Observable.create(observer -> {
Future<?> brighterFuture = executorService.submit(() -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
});
subscriber.add(Subscriptions.from(brighterFuture));
});
 Executes code in separate thread (from thread pool executorService)
 Stream of events is delivered by the executor thread
 Thread calling onNext() runs all the operations defined on observable
 Future is cancelled if client unsubscribes
CREATING OBSERVABLES
Observable<Boolean> watchTheCat =
Observable.create(observer -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
})
.subscribeOn(scheduler);
 Subscribe function is executed on supplied scheduler (thin wrapper
over java.util.concurrent.Executor)
SUBSCRIPTION
public interface Subscription {
void unsubscribe();
boolean isUnsubscribed();
}
UNSUBSCRIBING
Observable.create(subscriber -> {
for (long i = 0; !subscriber.isUnsubscribed(); i++) {
subscriber.onNext(i);
System.out.println("Emitted: " + i);
}
subscriber.onCompleted();
})
.take(10)
.subscribe(aLong -> {
System.out.println("Got: " + aLong);
});
 Take operator unsubscribes from observable after 10 iterations
CONCURRENCY
 Synchronous vs. asynchonous, single or multiple threaded is
implementation detail of service provider (Observable)
 As long as onNext calls are not executed concurrently
 So the framework does not have to synchronize everything
 Operators combining many Observables ensure serialized access
 In face of misbehaving observable serialize() operator forces
correct behaviour
 Passing pure functions to Rx operators is always the best bet
LESSONS LEARNED
 In our use cases performance profile is dominated by other system
components
 Performance depends on implementation of used operators and
may vary
 Contention points on operators that merge streams
 Carelessly creating 1000s threads (one for each task) when
NewThreadScheduler used. Reaching `ulimit –u` - and system
almost freezes :)
 Current version (0.19) has very sane defaults though
 Debugging and reasoning about subscriptions is not always easy.
 Insert doOnEach or doOnNext calls for debugging
 IDE support not satisfactory, problems in placing breakpoints inside
closures – IntelliJ IDEA 13 has smart step into closures which my
help
MORE INFORMATION
 https://github.com/Netflix/RxJava
 https://github.com/Netflix/RxJava/wiki
 http://www.infoq.com/author/Erik-Meijer
 React conference
http://www.youtube.com/playlist?list=PLSD48HvrE7-
Z1stQ1vIIBumB0wK0s8llY
 Cat picture taken from http://www.teckler.com/en/Rapunzel
Reactive Java (33rd Degree)
source:
flatmapthatshit.com
REMEBER: DON’T ITERATE - FLATMAP

More Related Content

PDF
PPTX
Introduction to Spring Boot
PDF
Advanced task management with Celery
PDF
Sql query patterns, optimized
PPTX
Practical Kerberos with Apache HBase
PPT
Java database connectivity
PPTX
Design Beautiful REST + JSON APIs
PDF
What is REST API? REST API Concepts and Examples | Edureka
Introduction to Spring Boot
Advanced task management with Celery
Sql query patterns, optimized
Practical Kerberos with Apache HBase
Java database connectivity
Design Beautiful REST + JSON APIs
What is REST API? REST API Concepts and Examples | Edureka

What's hot (20)

PPT
Spring Core
PDF
REST API Best (Recommended) Practices
PDF
Android webservices
PDF
Pentesting GraphQL Applications
PPT
Hibernate architecture
PPT
Jsp java bean
PPTX
Mysql creating stored function
PPTX
Node.js Express
PDF
Learn REST in 18 Slides
PPTX
Multi-Tenancy with Spring Boot
PDF
Dongwon Kim – A Comparative Performance Evaluation of Flink
PPTX
Monitoramento de Banco de dados SQL Server com Zabbix
PDF
Sql Antipatterns Strike Back
PPTX
Local SQLite Database with Node for beginners
PDF
Remote Method Invocation in JAVA
PPTX
Elastic stack Presentation
PDF
Spring Boot
PDF
Swift Programming Language
PDF
Real Time Analytics: Algorithms and Systems
PDF
Ksug2015 - JPA3, JPA 내부구조
Spring Core
REST API Best (Recommended) Practices
Android webservices
Pentesting GraphQL Applications
Hibernate architecture
Jsp java bean
Mysql creating stored function
Node.js Express
Learn REST in 18 Slides
Multi-Tenancy with Spring Boot
Dongwon Kim – A Comparative Performance Evaluation of Flink
Monitoramento de Banco de dados SQL Server com Zabbix
Sql Antipatterns Strike Back
Local SQLite Database with Node for beginners
Remote Method Invocation in JAVA
Elastic stack Presentation
Spring Boot
Swift Programming Language
Real Time Analytics: Algorithms and Systems
Ksug2015 - JPA3, JPA 내부구조
Ad

Viewers also liked (20)

PPTX
Reactive Programming in Java 8 with Rx-Java
PPTX
Introduction to Reactive Java
PDF
Building Scalable Stateless Applications with RxJava
PDF
RxJava - introduction & design
PDF
Deep dive reactive java (DevoxxPl)
PPTX
Supercharged java 8 : with cyclops-react
PDF
Reactive Thinking in Java with RxJava2
PDF
AWS Java SDK @ scale
PPTX
Tusul bichih argachlal
PDF
Netherlands & Turkey
PPTX
Mini training - Reactive Extensions (Rx)
PPTX
Rx java in action
PDF
Owner - Java properties reinvented.
PPT
Offline powerpoint
PDF
Reactive design: languages, and paradigms
PDF
Java 8 Streams and Rx Java Comparison
PDF
Reactive Streams: Handling Data-Flow the Reactive Way
PPT
Agile QA presentation
PDF
Java 8 Stream API and RxJava Comparison
PPTX
RxJS In-Depth - AngularConnect 2015
Reactive Programming in Java 8 with Rx-Java
Introduction to Reactive Java
Building Scalable Stateless Applications with RxJava
RxJava - introduction & design
Deep dive reactive java (DevoxxPl)
Supercharged java 8 : with cyclops-react
Reactive Thinking in Java with RxJava2
AWS Java SDK @ scale
Tusul bichih argachlal
Netherlands & Turkey
Mini training - Reactive Extensions (Rx)
Rx java in action
Owner - Java properties reinvented.
Offline powerpoint
Reactive design: languages, and paradigms
Java 8 Streams and Rx Java Comparison
Reactive Streams: Handling Data-Flow the Reactive Way
Agile QA presentation
Java 8 Stream API and RxJava Comparison
RxJS In-Depth - AngularConnect 2015
Ad

Similar to Reactive Java (33rd Degree) (20)

PPTX
Reactive Java (GeeCON 2014)
PDF
RxJava for Android - GDG DevFest Ukraine 2015
PPTX
Rxjs marble-testing
PDF
Reactive Fault Tolerant Programming with Hystrix and RxJava
PDF
"Kotlin и rx в android" Дмитрий Воронин (Avito)
PPTX
PDF
Saving lives with rx java
PPTX
Rxandroid
PPTX
RxAndroid
PPTX
Reactive programming with RxAndroid
PPTX
Rxjs swetugg
PDF
Reactive programming on Android
PPTX
Rx – reactive extensions
PPTX
Rxjs ngvikings
PPTX
Akka.NET streams and reactive streams
PPTX
2 презентация rx java+android
PDF
Reactive x
PPTX
RxJava2 Slides
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PPTX
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Reactive Java (GeeCON 2014)
RxJava for Android - GDG DevFest Ukraine 2015
Rxjs marble-testing
Reactive Fault Tolerant Programming with Hystrix and RxJava
"Kotlin и rx в android" Дмитрий Воронин (Avito)
Saving lives with rx java
Rxandroid
RxAndroid
Reactive programming with RxAndroid
Rxjs swetugg
Reactive programming on Android
Rx – reactive extensions
Rxjs ngvikings
Akka.NET streams and reactive streams
2 презентация rx java+android
Reactive x
RxJava2 Slides
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM

More from Tomasz Kowalczewski (11)

PDF
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
PDF
How I learned to stop worrying and love the dark silicon apocalypse.pdf
PDF
Is writing performant code too expensive?
PDF
Is writing performant code too expensive?
PDF
Is writing performant code too expensive?
PDF
Everybody Lies
PDF
Forgive me for i have allocated
PPTX
Measure to fail
PPTX
Reactive Java at JDD 2014
PPTX
Java 8 jest tuż za rogiem
PPTX
Java gets a closure
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
How I learned to stop worrying and love the dark silicon apocalypse.pdf
Is writing performant code too expensive?
Is writing performant code too expensive?
Is writing performant code too expensive?
Everybody Lies
Forgive me for i have allocated
Measure to fail
Reactive Java at JDD 2014
Java 8 jest tuż za rogiem
Java gets a closure

Recently uploaded (20)

PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Transform Your Business with a Software ERP System
PDF
Nekopoi APK 2025 free lastest update
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Digital Strategies for Manufacturing Companies
PPT
Introduction Database Management System for Course Database
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
history of c programming in notes for students .pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Transform Your Business with a Software ERP System
Nekopoi APK 2025 free lastest update
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PTS Company Brochure 2025 (1).pdf.......
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Digital Strategies for Manufacturing Companies
Introduction Database Management System for Course Database
Navsoft: AI-Powered Business Solutions & Custom Software Development
history of c programming in notes for students .pptx
How Creative Agencies Leverage Project Management Software.pdf

Reactive Java (33rd Degree)

  • 2.  Reactive view of the world  Desgining interface for reactive interactions (the cat experiment)  Rx Java as implementation of that interface  Lessons learned STUFF I WILL TALK ABOUT
  • 3. REACTIVE “readily responsive to a stimulus” Merriam-Webster dictionary
  • 4. SYNCHRONOUS PULL COMMUNICATION Client Server Request Response Server processing Network latency
  • 6. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { boolean alive(); } public interface ShrödingersCat { Future<Boolean> alive(); } public interface ShrödingersCat { Iterator<Boolean> alive(); }
  • 8. PULL VS PUSH Observer Observable Subscribe ... onNext Server processing Network latency Maybe this one needs all the data...
  • 9. RX JAVA BY NETFLIX  Open source project with Apache License.  Java implementation of Rx Observables from Microsoft  The Netflix API uses it to make the entire service layer asynchronous  Provides a DSL for creating computation flows out of asynchronous sources using collection of operators for filtering, selecting, transforming and combining that flows in a lazy manner  These flows are called Observables – collection of events with push semantics (as oposed to pull in Iterator)  Targets the JVM not a language. Currently supports Java, Groovy, Clojure, and Scala
  • 10. OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); }
  • 11. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); } cat .alive() .subscribe(status -> System.out.println(status));
  • 12. public interface ShrödingersCat { Observable<Boolean> alive(); } cat .alive() .throttleWithTimeout(250, TimeUnit.MILLISECONDS) .distinctUntilChanged() .filter(isAlive -> isAlive) .map(Boolean::toString) .subscribe(status -> display.display(status)); SERVICE RETURNING OBSERVABLE
  • 13.  Maybe it executes its logic on subscriber thread?  Maybe it delegates part of the work to other threads?  Does it use NIO?  Maybe its an actor?  Does it return cached data?  Observer does not care! HOW IS THE OBSERVABLE IMPLEMENTED?
  • 19. Observable<ShrödingersCat> cats = listAllCats(); cats .flatMap(cat -> Observable .from(catService.getPicturesFor(cat)) .filter(image -> image.size() < 100 * 1000) ) ).subscribe(); FLATMAP(FUNC)
  • 20. CACHE Random random = new Random(); Observable<Integer> observable = Observable .range(1, 100) .map(random::nextInt) .cache(); observable.subscribe(System.out::println); observable.subscribe(System.out::println); ...  Always prints same values
  • 21. INJECTING CUSTOM OPERATORS USING LIFT class InternStrings implements Observable.Operator<String, String> { public Subscriber<String> call(Subscriber<String> subscriber) { return new Subscriber<String>() { public void onCompleted() { subscriber.onCompleted(); } public void onError(Throwable e) { subscriber.onError(e); } public void onNext(String s) { subscriber.onNext(s.intern()); }; } } Observable.from("AB", "CD", "AB", "DE") .lift(new InternStrings()) .subscribe();  Valuable for instrumentation  Inject debug code – see rxjava-contrib/rxjava-debug  Inject performance counters
  • 22. ERROR HANDLING  Correctly implemented observable will not produce any events after error notification  Operators available for fixing observables not adhering to this rule  Pass custom error handling function to subscribe  Transparently substite failing observable with another one  Convert error into regular event  Retry subscription in hope this time it will work...
  • 23. ESCAPING THE MONAD Iterable<String> strings = Observable.from(1, 2, 3, 4) .map(i -> Integer.toString(i)) .toBlockingObservable() .toIterable(); // or (and many more) T firstOrDefault(T defaultValue, Func1 predicate) Iterator<T> getIterator() Iterable<T> next()  Inverses the dependency, will wait for next item, then execute  Usually to interact with other, synchronous APIs  While migrating to reactive approach in small increments  To trigger early evaluation while debugging
  • 24. OBSERVER public interface Observer<T> { void onCompleted(); void onError(Throwable e); void onNext(T args); }
  • 25. CREATING OBSERVABLES Observable<Boolean> watchTheCat = Observable.create(observer -> { observer.onNext(cat.isAlive()); observer.onCompleted(); });  create accepts OnSubscribe function  Executed for every subscriber upon subscription  This example is not asynchronous
  • 26. CREATING OBSERVABLES Observable.create(observer -> { Future<?> brighterFuture = executorService.submit(() -> { observer.onNext(cat.isAlive()); observer.onCompleted(); }); subscriber.add(Subscriptions.from(brighterFuture)); });  Executes code in separate thread (from thread pool executorService)  Stream of events is delivered by the executor thread  Thread calling onNext() runs all the operations defined on observable  Future is cancelled if client unsubscribes
  • 27. CREATING OBSERVABLES Observable<Boolean> watchTheCat = Observable.create(observer -> { observer.onNext(cat.isAlive()); observer.onCompleted(); }) .subscribeOn(scheduler);  Subscribe function is executed on supplied scheduler (thin wrapper over java.util.concurrent.Executor)
  • 28. SUBSCRIPTION public interface Subscription { void unsubscribe(); boolean isUnsubscribed(); }
  • 29. UNSUBSCRIBING Observable.create(subscriber -> { for (long i = 0; !subscriber.isUnsubscribed(); i++) { subscriber.onNext(i); System.out.println("Emitted: " + i); } subscriber.onCompleted(); }) .take(10) .subscribe(aLong -> { System.out.println("Got: " + aLong); });  Take operator unsubscribes from observable after 10 iterations
  • 30. CONCURRENCY  Synchronous vs. asynchonous, single or multiple threaded is implementation detail of service provider (Observable)  As long as onNext calls are not executed concurrently  So the framework does not have to synchronize everything  Operators combining many Observables ensure serialized access  In face of misbehaving observable serialize() operator forces correct behaviour  Passing pure functions to Rx operators is always the best bet
  • 31. LESSONS LEARNED  In our use cases performance profile is dominated by other system components  Performance depends on implementation of used operators and may vary  Contention points on operators that merge streams  Carelessly creating 1000s threads (one for each task) when NewThreadScheduler used. Reaching `ulimit –u` - and system almost freezes :)  Current version (0.19) has very sane defaults though  Debugging and reasoning about subscriptions is not always easy.  Insert doOnEach or doOnNext calls for debugging  IDE support not satisfactory, problems in placing breakpoints inside closures – IntelliJ IDEA 13 has smart step into closures which my help
  • 32. MORE INFORMATION  https://github.com/Netflix/RxJava  https://github.com/Netflix/RxJava/wiki  http://www.infoq.com/author/Erik-Meijer  React conference http://www.youtube.com/playlist?list=PLSD48HvrE7- Z1stQ1vIIBumB0wK0s8llY  Cat picture taken from http://www.teckler.com/en/Rapunzel

Editor's Notes

  • #19: Transform the items emitted by an Observable into Observables, then flatten this into a single Observable