SlideShare a Scribd company logo
1 of 34
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
source:
flatmapthatshit.com
REMEBER: DON’T ITERATE - FLATMAP

More Related Content

What's hot

Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé Paumard
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsJorge Vásquez
 
Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Jean-Michel Doudoux
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorMax Huang
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programmingExotel
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquareApigee | Google Cloud
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and EffectsMartin Odersky
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The FutureTracy Lee
 

What's hot (20)

Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 
Angular 11
Angular 11Angular 11
Angular 11
 
Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring Reactor
 
ClassLoader Leaks
ClassLoader LeaksClassLoader Leaks
ClassLoader Leaks
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
REST API
REST APIREST API
REST API
 
Retrofit
RetrofitRetrofit
Retrofit
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 

Viewers also liked

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-JavaKasun Indrasiri
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
RxJava - introduction & design
RxJava - introduction & designRxJava - introduction & design
RxJava - introduction & designallegro.tech
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Tomasz Kowalczewski
 
Supercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactSupercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactJohn McClean
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Tusul bichih argachlal
Tusul bichih argachlalTusul bichih argachlal
Tusul bichih argachlalCopy Mn
 
Netherlands & Turkey
Netherlands & TurkeyNetherlands & Turkey
Netherlands & TurkeyRoel Palmaers
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
Offline powerpoint
Offline powerpointOffline powerpoint
Offline powerpointmoejarv
 
Reactive design: languages, and paradigms
Reactive design: languages, and paradigmsReactive design: languages, and paradigms
Reactive design: languages, and paradigmsDean Wampler
 
Java 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java ComparisonJava 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java ComparisonJosé Paumard
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 
Agile QA presentation
Agile QA presentationAgile QA presentation
Agile QA presentationCarl Bruiners
 
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 ComparisonJosé Paumard
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 

Viewers also liked (20)

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
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
RxJava - introduction & design
RxJava - introduction & designRxJava - introduction & design
RxJava - introduction & design
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)
 
Supercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactSupercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-react
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Tusul bichih argachlal
Tusul bichih argachlalTusul bichih argachlal
Tusul bichih argachlal
 
Netherlands & Turkey
Netherlands & TurkeyNetherlands & Turkey
Netherlands & Turkey
 
Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
Offline powerpoint
Offline powerpointOffline powerpoint
Offline powerpoint
 
Reactive design: languages, and paradigms
Reactive design: languages, and paradigmsReactive design: languages, and paradigms
Reactive design: languages, and paradigms
 
Java 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java ComparisonJava 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java Comparison
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 
Agile QA presentation
Agile QA presentationAgile QA presentation
Agile QA presentation
 
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
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 

Similar to Reactive Java (33rd Degree)

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
 
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 RxJavaMatt Stine
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
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
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on AndroidGuilherme Branco
 

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

Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
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
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
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
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
Reactive x
Reactive xReactive x
Reactive x
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
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...
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
 

More from Tomasz Kowalczewski

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.pdfHow I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfTomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?Tomasz Kowalczewski
 

More from Tomasz Kowalczewski (10)

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.pdfHow 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
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?
 
Everybody Lies
Everybody LiesEverybody Lies
Everybody Lies
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
Measure to fail
Measure to failMeasure to fail
Measure to fail
 
Reactive Java at JDD 2014
Reactive Java at JDD 2014Reactive Java at JDD 2014
Reactive Java at JDD 2014
 
Java 8 jest tuż za rogiem
Java 8 jest tuż za rogiemJava 8 jest tuż za rogiem
Java 8 jest tuż za rogiem
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

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
  • 33.

Editor's Notes

  1. Transform the items emitted by an Observable into Observables, then flatten this into a single Observable