SlideShare une entreprise Scribd logo
1  sur  32
TOMASZ KOWALCZEWSKI
REACTIVE JAVA
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 ->
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();
}
REACTIVE
“readily responsive to a stimulus”
Merriam-Webster dictionary
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
Observable<Boolean> alive();
}
SUBCRIPTIONS AND EVENTS
t
subscribe
onNext*
onCompleted | onError
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
DEBOUNCE(LONG TIMEOUT, TIMEUNIT TU)
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();
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
 Some operators require scheduler, default is NewThreadScheduler
 Creating 1000s of threads and reaching `ulimit –u` - system
almost freezes :)
 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

Contenu connexe

Tendances

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
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
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 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
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
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaFabio Collini
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
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 programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 

Tendances (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
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
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
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
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
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 

En vedette

Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)GlobalLogic Ukraine
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Jean-Paul Calbimonte
 
RDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsRDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsJean-Paul Calbimonte
 
Colombia career market 01.27.2015
Colombia career market 01.27.2015Colombia career market 01.27.2015
Colombia career market 01.27.2015Felipe Saenz M
 
Final - advertising
Final - advertisingFinal - advertising
Final - advertisingasofaihp
 
Something from nothing
Something from nothingSomething from nothing
Something from nothingmsourgiad
 
Get your facebook out of my twitter
Get your facebook out of my twitterGet your facebook out of my twitter
Get your facebook out of my twitterprofessormedic
 
Co to jest iPresso?
Co to jest iPresso?Co to jest iPresso?
Co to jest iPresso?iPresso
 
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideA Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideP9P
 
Social studies chap 1 subject 1
Social studies chap 1  subject 1Social studies chap 1  subject 1
Social studies chap 1 subject 1Gladimar Marín
 
Badminton by Molly Naylor
Badminton by Molly NaylorBadminton by Molly Naylor
Badminton by Molly NaylorBurning Eye
 
Peperiksaan ptd 2012
Peperiksaan ptd 2012Peperiksaan ptd 2012
Peperiksaan ptd 2012exam_ptd_2012
 

En vedette (20)

Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015
 
RDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsRDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementations
 
Ldap howto
Ldap howtoLdap howto
Ldap howto
 
Webcasting
WebcastingWebcasting
Webcasting
 
Ptd m41 2012
Ptd m41 2012Ptd m41 2012
Ptd m41 2012
 
Colombia career market 01.27.2015
Colombia career market 01.27.2015Colombia career market 01.27.2015
Colombia career market 01.27.2015
 
Final - advertising
Final - advertisingFinal - advertising
Final - advertising
 
Something from nothing
Something from nothingSomething from nothing
Something from nothing
 
Question 4
Question 4Question 4
Question 4
 
Making waves
Making wavesMaking waves
Making waves
 
Get your facebook out of my twitter
Get your facebook out of my twitterGet your facebook out of my twitter
Get your facebook out of my twitter
 
Mobile money 2015
Mobile money 2015Mobile money 2015
Mobile money 2015
 
Co to jest iPresso?
Co to jest iPresso?Co to jest iPresso?
Co to jest iPresso?
 
Q3
Q3Q3
Q3
 
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideA Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
 
Social studies chap 1 subject 1
Social studies chap 1  subject 1Social studies chap 1  subject 1
Social studies chap 1 subject 1
 
Badminton by Molly Naylor
Badminton by Molly NaylorBadminton by Molly Naylor
Badminton by Molly Naylor
 
Peperiksaan ptd 2012
Peperiksaan ptd 2012Peperiksaan ptd 2012
Peperiksaan ptd 2012
 

Similaire à Reactive Java (GeeCON 2014)

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftAaron Douglas
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiNexus FrontierTech
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
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
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixTracy Lee
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUIkiahiska
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
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
 
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
 

Similaire à Reactive Java (GeeCON 2014) (20)

Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
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...
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
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
 
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
 

Plus de Tomasz Kowalczewski

Plus de Tomasz Kowalczewski (12)

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?
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)
 
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
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
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
 

Dernier

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Dernier (20)

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

Reactive Java (GeeCON 2014)

  • 2. 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
  • 3.
  • 6. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { boolean alive(); } public interface ShrödingersCat { Future<Boolean> alive(); } public interface ShrödingersCat { Iterator<Boolean> alive(); }
  • 7. REACTIVE “readily responsive to a stimulus” Merriam-Webster dictionary
  • 8. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); }
  • 10. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); } cat .alive() .subscribe(status -> System.out.println(status));
  • 11. 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
  • 12.  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?
  • 18. Observable<ShrödingersCat> cats = listAllCats(); cats .flatMap(cat -> Observable .from(catService.getPicturesFor(cat)) .filter(image -> image.size() < 100 * 1000) ) ).subscribe(); FLATMAP(FUNC)
  • 19. 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();
  • 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  Some operators require scheduler, default is NewThreadScheduler  Creating 1000s of threads and reaching `ulimit –u` - system almost freezes :)  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