SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
by Mario Fusco
mario.fusco@gmail.com
@mariofusco
Reactive Programming
for a demanding world:
building event-driven and
responsive applications with
RxJava
Reactive
“readily responsive to a stimulus”
Merriam-Webster dictionary
Why reactive? What changed?
➢ Usage patterns: Users expect millisecond response times and 100% uptime
A few years ago largest applications had tens of servers and gigabytes of data
Seconds of response time and hours of offline maintenance were acceptable
Today
➢ Big Data: usually measured in Petabytes and
increasing with an extremely high frequency
➢ Heterogeneous environment: applications are deployed
on everything from mobile devices to cloud-based
clusters running thousands of multi-core processors
Today's demands are simply not met
by yesterday’s software architectures!
The Reactive Manifesto
The system responds in a timely manner
if at all possible. Responsiveness is the
cornerstone of usability The system stays
responsive in the
face of failure
The system stays
responsive under varying
workload. It can react to
changes in the input rate
by increasing or decreasing
the resources allocated to
service these inputs
The system rely on asynchronous message
passing to establish a boundary between
components that ensures loose coupling,
isolation and location transparency
Responsive
Resilient
Message Driven
Elastic
The Reactive Streams Initiative
Reactive Streams is an initiative to provide a standard for asynchronous
stream processing with non-blocking back pressure on the JVM
Problem
Handling streams of (live) data
in an asynchronous and
possibly non-blocking way
Scope
Finding a minimal API
describing the operations
available on Reactive Streams
Implementors
Akka Streams
Reactor Composable
RxJava
Ratpack
Rethinking programming the
Reactive way
➢ Reactive programming is a programming paradigm about data-flow
➢ Think in terms of discrete events and streams of them
➢ React to events and define behaviors combining them
➢ The system state changes over time based on the flow of events
➢ Keep your data/events immutable
Never
block!
Reactive programming is
programming with
asynchronous data streams
➢ A stream is a sequence
of ongoing events
ordered in time
➢ Events are processed
asynchronously, by
defining a function
that will be executed
when an event arrives
See Events Streams Everywhere
stock prices
weather
shop's
orders
flights/trains arrivals
time
mouse position
Reactive Programming Mantra
Streams are not collections
Streams are
➢ potentially unbounded in length
➢ focused on transformation of data
➢ time-dependent
➢ ephemeral
➢ traversable only once
«You cannot step twice into the same
stream. For as you are stepping in, other
waters are ever flowing on to you.»
— Heraclitus
RxJava
Reactive Extension for async programming
➢ A library for composing asynchronous and event-based
programs using observable sequences for the Java VM
➢ Supports Java 6 or higher and JVM-based languages such as
Groovy, Clojure, JRuby, Kotlin and Scala
➢ Includes a DSL providing extensive operations for streams
transformation, filtering and recombination
➢ Implements pure “push” model
➢ Decouple events production from consumption
➢ Allows blocking only for back pressure
➢ First class support for error handling,
scheduling & flow control
➢ Used by Netflix to make the entire service
layer asynchronous
http://reactivex.io
http://github.com/ReactiveX/RxJava
How Netflix uses RxJava
From N network call ...
… to only 1
Pushing client logic to server
Marble diagrams:
Representing events' streams ...
A stream is a sequence of ongoing events ordered in time.
It can emit three different things:
1. a value (of some type) 2. an error 3. "completed" signal
… and events' transformations
RxJava operations as marble diagrams
Observable
The Observable interface defines how to access
asynchronous sequences of multiple items
single value multiple values
synchronous T getData() Iterable<T> getData()
asynchronous Future<T> getData() Observable<T> getData()
An Observable is the asynchronous/push “dual” to the synchronous/pull Iterable
Iterable (pull) Obesrvable (push)
retrieve data T next() onNext(T)
signal error throws Exception onError(Exception)
completion !hasNext() onCompleted()
Observable as async Stream
// Stream<Stock> containing 100 Stocks
getDataFromLocalMemory()
.skip(10)
.filter(s -> s.getValue > 100)
.map(s -> s.getName() + “: ” + s.getValue())
.forEach(System.out::println);
// Observable<Stock> emitting 100 Stocks
getDataFromNetwork()
.skip(10)
.filter(s -> s.getValue > 100)
.map(s -> s.getName() + “: ” + s.getValue())
.forEach(System.out::println);
Observable and Concurrency
An Observable is sequential → No concurrent emissions
Scheduling and combining Observables enables
concurrency while retaining sequential emission
Reactive Programming
requires a mental shift
from sync to async
from pull to push
from imperative to functional
Observing an Observable
Observer
Observable
time
subscribe
onNext*
onError | onCompleted
How is the Observable implemented?
➢ Maybe it executes its logic on subscriber thread?
➢ Maybe it delegates part of the work to other threads?
➢ Does it use NIO?
➢ Maybe it is an actor?
➢ Does it return cached data?
Observer
does not
care!
public interface Observer<T> {
void onCompleted();
void onError(Throwable var1);
void onNext(T var1);
}
Non-Opinionated Concurrency
Observable Observer
Calling
Thread
Callback
Thread
onNext
Work synchronously on calling thread
Observable Observer
Calling
Thread
Callback
Thread
onNext
Work asynchronously on separate thread
Thread pool
Observable Observer
Calling
Thread Callback
Threads
onNext
Work asynchronously on multiple threads
Thread pool
Could be an actor or an event loop
Enough speaking
Show me the code!
public class TempInfo {
public static final Random random = new Random();
public final String town;
public final int temp;
public TempInfo(String town, int temp) {
this.town = town;
this.temp = temp;
}
public static TempInfo fetch(String temp) {
return new TempInfo(temp, random.nextInt(70) - 20);
}
@Override
public String toString() {
return String.format(town + " : " + temp);
}
}
Fetching town's temperature
Creating Observables ...
public static Observable<TempInfo> getTemp(String town) {
return Observable.just(TempInfo.fetch(town));
}
public static Observable<TempInfo> getTemps(String... towns) {
return Observable.from(Stream.of(towns)
.map(town -> TempInfo.fetch(town))
.collect(toList()));
}
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(subscriber -> {
while (true) {
subscriber.onNext(TempInfo.fetch(town));
Thread.sleep(1000);
}
});
}
➢ … with just a single value
➢ … from an Iterable
➢ … from another Observable
Combining Observables
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(
subscriber -> Observable.interval(1, TimeUnit.SECONDS)
.subscribe(i -> subscriber
.onNext(TempInfo.fetch(town))));
}
public static Observable<TempInfo> getFeeds(String... towns) {
return Observable.merge(Arrays.stream(towns)
.map(town -> getFeed(town))
.collect(toList()));
}
➢ Subscribing one Observable to another
➢ Merging more Observables
Managing errors and completion
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(subscriber ->
Observable.interval(1, TimeUnit.SECONDS)
.subscribe(i -> {
if (i > 5) subscriber.onCompleted();
try {
subscriber.onNext(TempInfo.fetch(town));
} catch (Exception e) {
subscriber.onError(e);
}
}));
}
Observable<TempInfo> feed = getFeeds("Milano", "Roma", "Napoli");
feed.subscribe(new Observer<TempInfo>() {
public void onCompleted() { System.out.println("Done!"); }
public void onError(Throwable t) {
System.out.println("Got problem: " + t);
}
public void onNext(TempInfo t) { System.out.println(t); }
});
Hot & Cold Observables
HOT
emits immediately whether its
Observer is ready or not
examples
mouse & keyboard events
system events
stock prices
time
COLD
emits at controlled rate when
requested by its Observers
examples
in-memory Iterable
database query
web service request
reading file
Dealing with a slow consumer
Push (reactive) when consumer keeps up with producer
Switch to Pull (interactive) when consumer is slow
observable.subscribe(new Subscriber<T>() {
@Override public void onStart() { request(1); }
@Override
public void onCompleted() { /* handle sequence-complete */ }
@Override
public void onError(Throwable e) { /* handle error */ }
@Override public void onNext(T n) {
// do something with the emitted item
request(1); // request another item
}
});
When you subscribe to an
Observable, you can request
reactive pull backpressure
Backpressure
Reactive pull
backpressure
isn’t magic
Backpressure doesn’t
make the problem of
an overproducing
Observable or an
underconsuming
Subscriber go away.
It just moves the
problem up the chain
of operators to a
point where it can be
handled better.
Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Q A
Thanks … Questions?

Contenu connexe

Tendances

Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...
Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...
Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...confluent
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorVMware Tanzu
 
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
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producerconfluent
 
Testing Kafka containers with Testcontainers: There and back again with Vikto...
Testing Kafka containers with Testcontainers: There and back again with Vikto...Testing Kafka containers with Testcontainers: There and back again with Vikto...
Testing Kafka containers with Testcontainers: There and back again with Vikto...HostedbyConfluent
 
An Introduction to Apache Kafka
An Introduction to Apache KafkaAn Introduction to Apache Kafka
An Introduction to Apache KafkaAmir Sedighi
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programmingDwi Randy Herdinanto
 
Real World Event Sourcing and CQRS
Real World Event Sourcing and CQRSReal World Event Sourcing and CQRS
Real World Event Sourcing and CQRSMatthew Hawkins
 
Fundamentals of Apache Kafka
Fundamentals of Apache KafkaFundamentals of Apache Kafka
Fundamentals of Apache KafkaChhavi Parasher
 
So You Want to Write a Connector?
So You Want to Write a Connector? So You Want to Write a Connector?
So You Want to Write a Connector? confluent
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCShiju Varghese
 
How Apache Kafka® Works
How Apache Kafka® WorksHow Apache Kafka® Works
How Apache Kafka® Worksconfluent
 
Introduction to Kafka connect
Introduction to Kafka connectIntroduction to Kafka connect
Introduction to Kafka connectKnoldus Inc.
 

Tendances (20)

Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...
Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...
Simplifying Distributed Transactions with Sagas in Kafka (Stephen Zoio, Simpl...
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
 
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
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producer
 
Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
 
Kafka presentation
Kafka presentationKafka presentation
Kafka presentation
 
Testing Kafka containers with Testcontainers: There and back again with Vikto...
Testing Kafka containers with Testcontainers: There and back again with Vikto...Testing Kafka containers with Testcontainers: There and back again with Vikto...
Testing Kafka containers with Testcontainers: There and back again with Vikto...
 
An Introduction to Apache Kafka
An Introduction to Apache KafkaAn Introduction to Apache Kafka
An Introduction to Apache Kafka
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programming
 
Real World Event Sourcing and CQRS
Real World Event Sourcing and CQRSReal World Event Sourcing and CQRS
Real World Event Sourcing and CQRS
 
Fundamentals of Apache Kafka
Fundamentals of Apache KafkaFundamentals of Apache Kafka
Fundamentals of Apache Kafka
 
So You Want to Write a Connector?
So You Want to Write a Connector? So You Want to Write a Connector?
So You Want to Write a Connector?
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPC
 
How Apache Kafka® Works
How Apache Kafka® WorksHow Apache Kafka® Works
How Apache Kafka® Works
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafka
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Kafka connect
Introduction to Kafka connectIntroduction to Kafka connect
Introduction to Kafka connect
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 

En vedette

Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudBen Wilcock
 
Introduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationIntroduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationBorislav Markov
 
Introduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming PoznanIntroduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming PoznanEliasz Sawicki
 
Spring integration with the Java DSL
Spring integration with the Java DSLSpring integration with the Java DSL
Spring integration with the Java DSLBen Wilcock
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Microservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingMicroservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingBen Wilcock
 
Integration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices ArchitecturesIntegration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices ArchitecturesApcera
 
Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015Aviran Mordo
 

En vedette (8)

Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloud
 
Introduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationIntroduction to Kafka with Spring Integration
Introduction to Kafka with Spring Integration
 
Introduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming PoznanIntroduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming Poznan
 
Spring integration with the Java DSL
Spring integration with the Java DSLSpring integration with the Java DSL
Spring integration with the Java DSL
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Microservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingMicroservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event Sourcing
 
Integration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices ArchitecturesIntegration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices Architectures
 
Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015
 

Similaire à Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava

Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Codemotion
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...GeeksLab Odessa
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)Sharma Podila
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''OdessaJS Conf
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
Apache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsStephan Ewen
 
Reactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsDean Wampler
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flinkRenato Guimaraes
 
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
 
Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseKostas Tzoumas
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Apache Flink Stream Processing
Apache Flink Stream ProcessingApache Flink Stream Processing
Apache Flink Stream ProcessingSuneel Marthi
 
Apache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault ToleranceApache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault ToleranceSachin Aggarwal
 

Similaire à Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava (20)

Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Apache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and Friends
 
Reactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka Streams
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
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
 
Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San Jose
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Apache Flink Stream Processing
Apache Flink Stream ProcessingApache Flink Stream Processing
Apache Flink Stream Processing
 
Apache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault ToleranceApache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault Tolerance
 

Plus de Mario Fusco

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automationMario Fusco
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep diveMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageMario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 

Plus de Mario Fusco (20)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Lazy java
Lazy javaLazy java
Lazy java
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 

Dernier

Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationMarko4394
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 

Dernier (17)

Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentation
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 

Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava

  • 1. by Mario Fusco mario.fusco@gmail.com @mariofusco Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava
  • 2. Reactive “readily responsive to a stimulus” Merriam-Webster dictionary
  • 3. Why reactive? What changed? ➢ Usage patterns: Users expect millisecond response times and 100% uptime A few years ago largest applications had tens of servers and gigabytes of data Seconds of response time and hours of offline maintenance were acceptable Today ➢ Big Data: usually measured in Petabytes and increasing with an extremely high frequency ➢ Heterogeneous environment: applications are deployed on everything from mobile devices to cloud-based clusters running thousands of multi-core processors Today's demands are simply not met by yesterday’s software architectures!
  • 4. The Reactive Manifesto The system responds in a timely manner if at all possible. Responsiveness is the cornerstone of usability The system stays responsive in the face of failure The system stays responsive under varying workload. It can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs The system rely on asynchronous message passing to establish a boundary between components that ensures loose coupling, isolation and location transparency Responsive Resilient Message Driven Elastic
  • 5. The Reactive Streams Initiative Reactive Streams is an initiative to provide a standard for asynchronous stream processing with non-blocking back pressure on the JVM Problem Handling streams of (live) data in an asynchronous and possibly non-blocking way Scope Finding a minimal API describing the operations available on Reactive Streams Implementors Akka Streams Reactor Composable RxJava Ratpack
  • 6. Rethinking programming the Reactive way ➢ Reactive programming is a programming paradigm about data-flow ➢ Think in terms of discrete events and streams of them ➢ React to events and define behaviors combining them ➢ The system state changes over time based on the flow of events ➢ Keep your data/events immutable Never block!
  • 7. Reactive programming is programming with asynchronous data streams ➢ A stream is a sequence of ongoing events ordered in time ➢ Events are processed asynchronously, by defining a function that will be executed when an event arrives
  • 8. See Events Streams Everywhere stock prices weather shop's orders flights/trains arrivals time mouse position
  • 10. Streams are not collections Streams are ➢ potentially unbounded in length ➢ focused on transformation of data ➢ time-dependent ➢ ephemeral ➢ traversable only once «You cannot step twice into the same stream. For as you are stepping in, other waters are ever flowing on to you.» — Heraclitus
  • 11. RxJava Reactive Extension for async programming ➢ A library for composing asynchronous and event-based programs using observable sequences for the Java VM ➢ Supports Java 6 or higher and JVM-based languages such as Groovy, Clojure, JRuby, Kotlin and Scala ➢ Includes a DSL providing extensive operations for streams transformation, filtering and recombination ➢ Implements pure “push” model ➢ Decouple events production from consumption ➢ Allows blocking only for back pressure ➢ First class support for error handling, scheduling & flow control ➢ Used by Netflix to make the entire service layer asynchronous http://reactivex.io http://github.com/ReactiveX/RxJava
  • 12. How Netflix uses RxJava From N network call ...
  • 13. … to only 1 Pushing client logic to server
  • 14. Marble diagrams: Representing events' streams ... A stream is a sequence of ongoing events ordered in time. It can emit three different things: 1. a value (of some type) 2. an error 3. "completed" signal
  • 15. … and events' transformations
  • 16. RxJava operations as marble diagrams
  • 17. Observable The Observable interface defines how to access asynchronous sequences of multiple items single value multiple values synchronous T getData() Iterable<T> getData() asynchronous Future<T> getData() Observable<T> getData() An Observable is the asynchronous/push “dual” to the synchronous/pull Iterable Iterable (pull) Obesrvable (push) retrieve data T next() onNext(T) signal error throws Exception onError(Exception) completion !hasNext() onCompleted()
  • 18. Observable as async Stream // Stream<Stock> containing 100 Stocks getDataFromLocalMemory() .skip(10) .filter(s -> s.getValue > 100) .map(s -> s.getName() + “: ” + s.getValue()) .forEach(System.out::println); // Observable<Stock> emitting 100 Stocks getDataFromNetwork() .skip(10) .filter(s -> s.getValue > 100) .map(s -> s.getName() + “: ” + s.getValue()) .forEach(System.out::println);
  • 19. Observable and Concurrency An Observable is sequential → No concurrent emissions Scheduling and combining Observables enables concurrency while retaining sequential emission
  • 20. Reactive Programming requires a mental shift from sync to async from pull to push from imperative to functional
  • 22. How is the Observable implemented? ➢ Maybe it executes its logic on subscriber thread? ➢ Maybe it delegates part of the work to other threads? ➢ Does it use NIO? ➢ Maybe it is an actor? ➢ Does it return cached data? Observer does not care! public interface Observer<T> { void onCompleted(); void onError(Throwable var1); void onNext(T var1); }
  • 23. Non-Opinionated Concurrency Observable Observer Calling Thread Callback Thread onNext Work synchronously on calling thread Observable Observer Calling Thread Callback Thread onNext Work asynchronously on separate thread Thread pool Observable Observer Calling Thread Callback Threads onNext Work asynchronously on multiple threads Thread pool Could be an actor or an event loop
  • 25. public class TempInfo { public static final Random random = new Random(); public final String town; public final int temp; public TempInfo(String town, int temp) { this.town = town; this.temp = temp; } public static TempInfo fetch(String temp) { return new TempInfo(temp, random.nextInt(70) - 20); } @Override public String toString() { return String.format(town + " : " + temp); } } Fetching town's temperature
  • 26. Creating Observables ... public static Observable<TempInfo> getTemp(String town) { return Observable.just(TempInfo.fetch(town)); } public static Observable<TempInfo> getTemps(String... towns) { return Observable.from(Stream.of(towns) .map(town -> TempInfo.fetch(town)) .collect(toList())); } public static Observable<TempInfo> getFeed(String town) { return Observable.create(subscriber -> { while (true) { subscriber.onNext(TempInfo.fetch(town)); Thread.sleep(1000); } }); } ➢ … with just a single value ➢ … from an Iterable ➢ … from another Observable
  • 27. Combining Observables public static Observable<TempInfo> getFeed(String town) { return Observable.create( subscriber -> Observable.interval(1, TimeUnit.SECONDS) .subscribe(i -> subscriber .onNext(TempInfo.fetch(town)))); } public static Observable<TempInfo> getFeeds(String... towns) { return Observable.merge(Arrays.stream(towns) .map(town -> getFeed(town)) .collect(toList())); } ➢ Subscribing one Observable to another ➢ Merging more Observables
  • 28. Managing errors and completion public static Observable<TempInfo> getFeed(String town) { return Observable.create(subscriber -> Observable.interval(1, TimeUnit.SECONDS) .subscribe(i -> { if (i > 5) subscriber.onCompleted(); try { subscriber.onNext(TempInfo.fetch(town)); } catch (Exception e) { subscriber.onError(e); } })); } Observable<TempInfo> feed = getFeeds("Milano", "Roma", "Napoli"); feed.subscribe(new Observer<TempInfo>() { public void onCompleted() { System.out.println("Done!"); } public void onError(Throwable t) { System.out.println("Got problem: " + t); } public void onNext(TempInfo t) { System.out.println(t); } });
  • 29. Hot & Cold Observables HOT emits immediately whether its Observer is ready or not examples mouse & keyboard events system events stock prices time COLD emits at controlled rate when requested by its Observers examples in-memory Iterable database query web service request reading file
  • 30. Dealing with a slow consumer Push (reactive) when consumer keeps up with producer Switch to Pull (interactive) when consumer is slow observable.subscribe(new Subscriber<T>() { @Override public void onStart() { request(1); } @Override public void onCompleted() { /* handle sequence-complete */ } @Override public void onError(Throwable e) { /* handle error */ } @Override public void onNext(T n) { // do something with the emitted item request(1); // request another item } }); When you subscribe to an Observable, you can request reactive pull backpressure
  • 31. Backpressure Reactive pull backpressure isn’t magic Backpressure doesn’t make the problem of an overproducing Observable or an underconsuming Subscriber go away. It just moves the problem up the chain of operators to a point where it can be handled better.
  • 32. Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco Q A Thanks … Questions?