SlideShare a Scribd company logo
1 of 30
Download to read offline
Going Reactive with Java 8
Ryan Knight& Björn Antonsson
Users Want
In-SyncData
Real-time Collaboration
InstantFeedback
To NotWait
Users Want Reactive Apps
www.ReactiveManifesto.org
Reactive Web Apps with
Play Framework
http://www.playframework.com
Reactive Web Apps with
Play Framework
Reactive Requests
Reactive Composition
Reactive Push
2-Way Reactive
Routes
Declarative, Type-safe URLMapping
VERB PATH CONTROLLER_METHOD
GET / controllers.Application.index()
GET /foo controllers.Application.foo()
Controllers
Synchronous Request
Usefulforrequests thatdon`thave anything to notblock on
publicstaticResultsyncFoo(){
returnok("syncfoo");
}
Reactive Requests
Asynchronous Request
Underthe covers Play implements allrequests in this way
publicstaticF.Promise<Result>asyncFoo(){
returnF.Promise.promise(()->ok("asyncfoo"));
}
Reactive Request (Async + Non-
Blocking)
Needs to have something to notblock on
publicstaticIntegerlongRunningCalculation(){
return(5134*5789)/349;
}
publicstaticF.Promise<Result>basicPromise(){
F.Promise<Integer>promise=F.Promise.promise(()->longRunningCalculation());
returnpromise.map((Integeri)->ok("Thecalculationresultis:"+i));
}
Reactive Requests
Two chained requests (clientto server& serverto typesafe.com)
both async& non-blocking
publicstaticF.Promise<Result>reactiveRequest(){
F.Promise<WS.Response>typesafePromise=WS.url("http://www.typesafe.com").get();
returntypesafePromise.map(response->ok(response.getBody()));
}
Reactive Composition
Three requests, two in parrallel(depending on thread availability)
allasync& non-blocking
publicstaticF.Promise<Result>reactiveComposition(){
finalF.Promise<WS.Response>twitterPromise=WS.url("http://www.twitter.com").get();
finalF.Promise<WS.Response>typesafePromise=WS.url("http://www.typesafe.com").get();
returntwitterPromise.flatMap((twitter)->
typesafePromise.map((typesafe)->
ok(twitter.getBody()+typesafe.getBody())));
}
Reactive Push with SSE
Async& Non-Blocking Serverto ClientPush
JavaController
publicstaticResultevents(){
EventSourceeventSource=newEventSource(){
publicvoidonConnected(){
sendData("hello");
}
};
returnok(eventSource);
}
CoffeeScriptClient
events=newEventSource("/events")
events.onmessage=(e)->
alert(e.data)
2-Way Reactive with WebSockets
Bi-directionalreactive push
JavaControllerwithJava8MethodReference
publicstaticWebSocket<String>echo(){
returnnewWebSocket<String>(){
publicvoidonReady(finalIn<String>in,finalOut<String>out){
in.onMessage(out::write);
}
};
}
CoffeeScriptClient
ws=newWebSocket("ws://localhost:9000/echo")
ws.onmessage=(message)->
console.log(message.data)
ws.onopen=()->
ws.send("foo")
Reactive Apps with Akka
http://akka.io
Reactive Apps with Akka
ActorBased
Highly Concurrent
Asynchronous
Distributable
Scales Up & Out
Akka Actor Properties
Message Based
EventDriven
Sane Concurrency Model
Non-RequestBased Lifecycle
Isolated Failure Handling
(Supervision)
Actors with Lambdas
Easily define the behaviorof youractor
publicstaticclassGreeterextendsAbstractActor{
Stringgreeting="";
publicGreeter(){
receive(ReceiveBuilder.
match(WhoToGreet.class,message->greeting="hello,"+message.who).
match(Greet.class,message->sender().tell(newGreeting(greeting),self())).
build());
}
}
Handing off Work
Forresponsiveness and/orfaulttolerance
publicclassHandoffActorextendsAbstractActor{{
receive(ReceiveBuilder.matchEquals("hello",s->{
ActorRefworker=
context().actorOf(Props.create(AbstractActor.class,
()->newAbstractActor(){{
receive(ReceiveBuilder.
match(String.class,s->{
//longrunningand/ordangerouscomputation
sender().tell(s.toUpperCase(),self());
self().tell(PoisonPill.getInstance(),self());
}).build());
}}));
worker.forward(s,context());
}).build());
}}
Supervision with Lambdas
Take differentactions depending on the failure
privatestaticSupervisorStrategystrategy=
newOneForOneStrategy(10,Duration.create("1minute"),DeciderBuilder.
match(ArithmeticException.class,e->resume()).
match(NullPointerException.class,e->restart()).
match(IllegalArgumentException.class,e->stop()).
matchAny(o->escalate()).build());
@Override
publicSupervisorStrategysupervisorStrategy(){
returnstrategy;
}
Changing Behavior with Lambdas
Quickly implementchanges in behavior
publicclassSwapperextendsAbstractLoggingActor{
publicSwapper(){
receive(ReceiveBuilder.
matchEquals(Swap,s->{
log().info("Hi");
context().become(ReceiveBuilder.
matchEquals(Swap,x->{
log().info("Ho");
context().unbecome();//gobacktopreviousbehavior
}).build(),false);//pushontopandkeepoldbehavior
}).build());
}
}
Actors as Finite State
Machines
A Fixed Numberof States
Defined Transitions Between States
Used to ModelforExample
Protocols
Processes
Finite State Machines
Defining Behaviorin States
publicclassBuncherextendsAbstractFSM<State,Data>{{
startWith(Idle,Uninitialized);
when(Idle,
matchEvent(SetTarget.class,Uninitialized.class,
(setTarget,uninitialized)->
stay().using(newTodo(setTarget.getRef(),newLinkedList<>()))));
when(Active,Duration.create(1,"second"),
matchEvent(Arrays.asList(Flush.class,StateTimeout()),Todo.class,
(event,todo)->goTo(Idle).using(todo.copy(newLinkedList<>()))));
//...transitionsleftout
initialize();
}}
Finite State Machines
Defining Transition Behavior
publicclassBuncherextendsAbstractFSM<State,Data>{{
startWith(Idle,Uninitialized);
//...statebehaviorleftout
onTransition(
matchState(Active,Idle,()->{
//reusethismatcher
finalUnitMatch<Data>m=UnitMatch.create(
matchData(Todo.class,
todo->todo.getTarget().tell(newBatch(todo.getQueue()),self())));
m.match(stateData());
}).
state(Idle,Active,()->{/*Dosomethinghere*/}));
initialize();
}}
Interoperability
https://github.com/scala/scala-java8-compat
Java Scala Interoperability
Seamlessly Work with ScalaFutures
importscala.concurrent.*;
importstaticscala.compat.java8.JFunction.*;
classTest{
privatestaticFuture<Integer>futureExample(Future<String>future,ExecutionContextec){
returnfuture.map(func(s->s.toUpperCase()),ec).map(func(s->s.length()),ec);
}
}
Java Scala Interoperability
Seamlessly ConvertBetween JavaCompletionStage and Scala
Future
importjava.util.concurrent.CompletionStage;
importscala.concurrent.Future;
importstaticscala.compat.java8.FutureConverters.*;
finalCompletionStage<String>cs=...//fromanasyncJavaAPI
finalFuture<String>f=toScala(cs);
...
finalFuture<Integer>f2=...//fromanasyncScalaAPI
finalCompletionStage<Integer>cs2=toJava(f2);
Demo: Reactive Stocks (Java 8)
Getthe ActivatorTemplate:
http://typesafe.com/activator/template/reactive-stocks-java8
AkkaActors forthread-safe state and non-requestbased events
Play Framework forReactive Composition, Reactive Push, and a
JavaScriptUI
Reactive Stocks (Java8)
Get Started with Activator
http://typesafe.com/activator/template/hello-akka-java8
http://typesafe.com/activator/template/reactive-java8-play
http://typesafe.com/activator/template/akka-supervision-java-lambda
http://typesafe.com/activator/template/akka-sample-fsm-java-lambda
http://typesafe.com/activator/template/akka-sample-persistence-java-lambda
http://typesafe.com/activator/template/reactive-stocks-java8
Hello Akka!(Java8)
Go Reactive with Java8 & Play Framework
AkkaSupervision in Javawith Lambdas
AkkaFSMin Javawith Lambdas
AkkaPersistence Samples in Javawith Lambdas
Reactive Stocks (Java8)
Typesafe Webinar: Going Reactive with Java 8

More Related Content

Similar to Typesafe Webinar: Going Reactive with Java 8

The lazy programmers guide to consuming web services
The lazy programmers guide to consuming web services The lazy programmers guide to consuming web services
The lazy programmers guide to consuming web services mamnun
 
The Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane MaldiniThe Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane MaldiniVMware Tanzu
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularLoiane Groner
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web ApplicationsJames Da Costa
 
React vs angular (mobile first battle)
React vs angular (mobile first battle)React vs angular (mobile first battle)
React vs angular (mobile first battle)Michael Haberman
 
Connect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with JavascriptConnect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with Javascriptjoshcjensen
 
Taking Web Applications Offline
Taking Web Applications OfflineTaking Web Applications Offline
Taking Web Applications OfflineMatt Casto
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfFull-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfLoiane Groner
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for androidInnovationM
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In AndroidInnovationM
 
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java GirlFull-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java GirlLoiane Groner
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppAndolasoft Inc
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and ReduxMaxime Najim
 
PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事longfei.dong
 
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면jaemyun lee
 
Reactive programming for java developers
Reactive programming for java developersReactive programming for java developers
Reactive programming for java developersConstantin Popa
 
React & Redux in Hulu
React & Redux in HuluReact & Redux in Hulu
React & Redux in HuluMorgan Cheng
 
Do we still need a web framework ?
Do we still need a web framework ?Do we still need a web framework ?
Do we still need a web framework ?Mathieu Carbou
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?ConFoo
 

Similar to Typesafe Webinar: Going Reactive with Java 8 (20)

The lazy programmers guide to consuming web services
The lazy programmers guide to consuming web services The lazy programmers guide to consuming web services
The lazy programmers guide to consuming web services
 
The Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane MaldiniThe Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane Maldini
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + Angular
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web Applications
 
React vs angular (mobile first battle)
React vs angular (mobile first battle)React vs angular (mobile first battle)
React vs angular (mobile first battle)
 
Connect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with JavascriptConnect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with Javascript
 
Taking Web Applications Offline
Taking Web Applications OfflineTaking Web Applications Offline
Taking Web Applications Offline
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfFull-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In Android
 
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java GirlFull-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native App
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and Redux
 
Jsf
JsfJsf
Jsf
 
PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事
 
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
 
Reactive programming for java developers
Reactive programming for java developersReactive programming for java developers
Reactive programming for java developers
 
React & Redux in Hulu
React & Redux in HuluReact & Redux in Hulu
React & Redux in Hulu
 
Do we still need a web framework ?
Do we still need a web framework ?Do we still need a web framework ?
Do we still need a web framework ?
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?
 

Recently uploaded

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Recently uploaded (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Typesafe Webinar: Going Reactive with Java 8

  • 1. Going Reactive with Java 8 Ryan Knight& Björn Antonsson
  • 3. Users Want Reactive Apps www.ReactiveManifesto.org
  • 4. Reactive Web Apps with Play Framework http://www.playframework.com
  • 5. Reactive Web Apps with Play Framework Reactive Requests Reactive Composition Reactive Push 2-Way Reactive
  • 6. Routes Declarative, Type-safe URLMapping VERB PATH CONTROLLER_METHOD GET / controllers.Application.index() GET /foo controllers.Application.foo()
  • 7. Controllers Synchronous Request Usefulforrequests thatdon`thave anything to notblock on publicstaticResultsyncFoo(){ returnok("syncfoo"); }
  • 9. Asynchronous Request Underthe covers Play implements allrequests in this way publicstaticF.Promise<Result>asyncFoo(){ returnF.Promise.promise(()->ok("asyncfoo")); }
  • 10. Reactive Request (Async + Non- Blocking) Needs to have something to notblock on publicstaticIntegerlongRunningCalculation(){ return(5134*5789)/349; } publicstaticF.Promise<Result>basicPromise(){ F.Promise<Integer>promise=F.Promise.promise(()->longRunningCalculation()); returnpromise.map((Integeri)->ok("Thecalculationresultis:"+i)); }
  • 11. Reactive Requests Two chained requests (clientto server& serverto typesafe.com) both async& non-blocking publicstaticF.Promise<Result>reactiveRequest(){ F.Promise<WS.Response>typesafePromise=WS.url("http://www.typesafe.com").get(); returntypesafePromise.map(response->ok(response.getBody())); }
  • 12. Reactive Composition Three requests, two in parrallel(depending on thread availability) allasync& non-blocking publicstaticF.Promise<Result>reactiveComposition(){ finalF.Promise<WS.Response>twitterPromise=WS.url("http://www.twitter.com").get(); finalF.Promise<WS.Response>typesafePromise=WS.url("http://www.typesafe.com").get(); returntwitterPromise.flatMap((twitter)-> typesafePromise.map((typesafe)-> ok(twitter.getBody()+typesafe.getBody()))); }
  • 13. Reactive Push with SSE Async& Non-Blocking Serverto ClientPush JavaController publicstaticResultevents(){ EventSourceeventSource=newEventSource(){ publicvoidonConnected(){ sendData("hello"); } }; returnok(eventSource); } CoffeeScriptClient events=newEventSource("/events") events.onmessage=(e)-> alert(e.data)
  • 14. 2-Way Reactive with WebSockets Bi-directionalreactive push JavaControllerwithJava8MethodReference publicstaticWebSocket<String>echo(){ returnnewWebSocket<String>(){ publicvoidonReady(finalIn<String>in,finalOut<String>out){ in.onMessage(out::write); } }; } CoffeeScriptClient ws=newWebSocket("ws://localhost:9000/echo") ws.onmessage=(message)-> console.log(message.data) ws.onopen=()-> ws.send("foo")
  • 15. Reactive Apps with Akka http://akka.io
  • 16. Reactive Apps with Akka ActorBased Highly Concurrent Asynchronous Distributable Scales Up & Out
  • 17. Akka Actor Properties Message Based EventDriven Sane Concurrency Model Non-RequestBased Lifecycle Isolated Failure Handling (Supervision)
  • 18. Actors with Lambdas Easily define the behaviorof youractor publicstaticclassGreeterextendsAbstractActor{ Stringgreeting=""; publicGreeter(){ receive(ReceiveBuilder. match(WhoToGreet.class,message->greeting="hello,"+message.who). match(Greet.class,message->sender().tell(newGreeting(greeting),self())). build()); } }
  • 19. Handing off Work Forresponsiveness and/orfaulttolerance publicclassHandoffActorextendsAbstractActor{{ receive(ReceiveBuilder.matchEquals("hello",s->{ ActorRefworker= context().actorOf(Props.create(AbstractActor.class, ()->newAbstractActor(){{ receive(ReceiveBuilder. match(String.class,s->{ //longrunningand/ordangerouscomputation sender().tell(s.toUpperCase(),self()); self().tell(PoisonPill.getInstance(),self()); }).build()); }})); worker.forward(s,context()); }).build()); }}
  • 20. Supervision with Lambdas Take differentactions depending on the failure privatestaticSupervisorStrategystrategy= newOneForOneStrategy(10,Duration.create("1minute"),DeciderBuilder. match(ArithmeticException.class,e->resume()). match(NullPointerException.class,e->restart()). match(IllegalArgumentException.class,e->stop()). matchAny(o->escalate()).build()); @Override publicSupervisorStrategysupervisorStrategy(){ returnstrategy; }
  • 21. Changing Behavior with Lambdas Quickly implementchanges in behavior publicclassSwapperextendsAbstractLoggingActor{ publicSwapper(){ receive(ReceiveBuilder. matchEquals(Swap,s->{ log().info("Hi"); context().become(ReceiveBuilder. matchEquals(Swap,x->{ log().info("Ho"); context().unbecome();//gobacktopreviousbehavior }).build(),false);//pushontopandkeepoldbehavior }).build()); } }
  • 22. Actors as Finite State Machines A Fixed Numberof States Defined Transitions Between States Used to ModelforExample Protocols Processes
  • 23. Finite State Machines Defining Behaviorin States publicclassBuncherextendsAbstractFSM<State,Data>{{ startWith(Idle,Uninitialized); when(Idle, matchEvent(SetTarget.class,Uninitialized.class, (setTarget,uninitialized)-> stay().using(newTodo(setTarget.getRef(),newLinkedList<>())))); when(Active,Duration.create(1,"second"), matchEvent(Arrays.asList(Flush.class,StateTimeout()),Todo.class, (event,todo)->goTo(Idle).using(todo.copy(newLinkedList<>())))); //...transitionsleftout initialize(); }}
  • 24. Finite State Machines Defining Transition Behavior publicclassBuncherextendsAbstractFSM<State,Data>{{ startWith(Idle,Uninitialized); //...statebehaviorleftout onTransition( matchState(Active,Idle,()->{ //reusethismatcher finalUnitMatch<Data>m=UnitMatch.create( matchData(Todo.class, todo->todo.getTarget().tell(newBatch(todo.getQueue()),self()))); m.match(stateData()); }). state(Idle,Active,()->{/*Dosomethinghere*/})); initialize(); }}
  • 26. Java Scala Interoperability Seamlessly Work with ScalaFutures importscala.concurrent.*; importstaticscala.compat.java8.JFunction.*; classTest{ privatestaticFuture<Integer>futureExample(Future<String>future,ExecutionContextec){ returnfuture.map(func(s->s.toUpperCase()),ec).map(func(s->s.length()),ec); } }
  • 27. Java Scala Interoperability Seamlessly ConvertBetween JavaCompletionStage and Scala Future importjava.util.concurrent.CompletionStage; importscala.concurrent.Future; importstaticscala.compat.java8.FutureConverters.*; finalCompletionStage<String>cs=...//fromanasyncJavaAPI finalFuture<String>f=toScala(cs); ... finalFuture<Integer>f2=...//fromanasyncScalaAPI finalCompletionStage<Integer>cs2=toJava(f2);
  • 28. Demo: Reactive Stocks (Java 8) Getthe ActivatorTemplate: http://typesafe.com/activator/template/reactive-stocks-java8 AkkaActors forthread-safe state and non-requestbased events Play Framework forReactive Composition, Reactive Push, and a JavaScriptUI Reactive Stocks (Java8)
  • 29. Get Started with Activator http://typesafe.com/activator/template/hello-akka-java8 http://typesafe.com/activator/template/reactive-java8-play http://typesafe.com/activator/template/akka-supervision-java-lambda http://typesafe.com/activator/template/akka-sample-fsm-java-lambda http://typesafe.com/activator/template/akka-sample-persistence-java-lambda http://typesafe.com/activator/template/reactive-stocks-java8 Hello Akka!(Java8) Go Reactive with Java8 & Play Framework AkkaSupervision in Javawith Lambdas AkkaFSMin Javawith Lambdas AkkaPersistence Samples in Javawith Lambdas Reactive Stocks (Java8)