SlideShare a Scribd company logo
1 of 27
Ondrej Mihályi
Payara Services
How to Bake Reactive Behavior
into your Java EE Applications
@OMihalyi
Agenda
➢
Reactive Support in JavaEE7
➢
Java 8 goodness on Reactive
Implementations
➢
Payara Micro Additions
➢
Live demo
➢
Q&A
@OMihalyi
Reactive Manifesto
ResponsiveResponsive
ElasticElastic ResilientResilient
Message DrivenMessage Driven
@OMihalyi
Traditional approach
Request started
→ external resource required (DB, WS, files)
→ request external resource
→ external resource is slow
WHAT DO WE DO?
@OMihalyi
Traditional approach
WE SIMPLY WAIT…
@OMihalyi
Traditional approach
WE SIMPLY WAIT…
• Simple
• Thread-safe
• Often Sufficient (when waiting
time is negligible)
@OMihalyi
But…
@OMihalyi
But…
• … if waiting is too long
 Thread resources are wasted
 Processing may halt if all
threads waiting
@OMihalyi
Spawn a separate thread
• Idea:
- Blocking call in a new thread
- Do something while waiting
- Retrieve results
- Fail after timeout vs. block infinitely
- java.util.concurrent.Future
@OMihalyi
Drawbacks…
• Complexity
 keep asking “Are you ready?”
• Requires one more thread
 blocked while waiting
@OMihalyi
Finish in a new thread!
• Idea:
− Blocking call in another thread
− Transfer context to another thread
− No need to wait for the blocking
call
− But new thread may still be
blocked…
@OMihalyi
…and asynchronous calls
• Idea:
− Provide a callback
− Call finishes immediately
− Callback called in a new thread
− Finish request in the callback
− No need to wait at all
− But, is it possible?
@OMihalyi
Asynchronous API in Java EE
• Async Servlet request completion
• Async JAX-RS request completion
• Async JAX-RS client
• Async IO in Servlet
• Async EJB calls
• Managed Executors
• WebSockets
@OMihalyi
Async API Example
• JAX-RS AsyncResponse @Suspended
@GET
void get(@Suspended
AsyncResponse response)
…
response.resume("OK");
@OMihalyi
Async API Example
• JAX-RS async client
resourceTarget
.request(MediaType.TEXT_PLAIN)
.async()
.get(
new InvocationCallback() …
@OMihalyi
Java EE + Java 8
• Future → CompletableFuture ?
− No, not compatible
• Callbacks → CompletableFuture
− callback triggers cf.complete()
• Pass CF as additional parameter to
complete it later
@OMihalyi
Pass CF as additional parameter
cf = new CompletableFuture<...>();
webtarget.async()
.get(new InvocationCallback() {
… cf.complete(result); …
});
cf.thenAccept(result -> …)
@OMihalyi
CompletableFuture
− Chain callbacks (like promises)
●
thenRun(), thenApply(), …
●
thenCompose()
− Complete execution in any thread
●
compFuture.complete()
@OMihalyi
Concurrency utilities
ctxSvc.createContextualProxy(
() -> {…wrapped code…},Runnable.class})
• Requests span multiple threads
• Context must be retained
• Managed threads (ExecutorService)
• ContextService for non-managed
@OMihalyi
Live Demo
• Revisit famous cargo-tracker in a reactive way
Available at:
https://github.com/OndrejM-demonstrations/Reactive-CargoTracker
@OMihalyi
●
Other parts of being Reactive
• We’ve shown responsive API
• The other 3 reactive concepts:
−Resilience
−Messaging
−Elasticity
@OMihalyi
Payara Micro
• Application server as executable JAR
• Runs WAR apps from command line
• automatic and elastic clustering
→ spawn many micro services dynamically
→ replication using distributed cache
→ shared 60MB runtime, 40MB in heap
www.payara.fish
@OMihalyi
• Simple messaging and caching
@Inject @Outbound
Event<MyMsg> ev;
// handle in different JVM
void handle(@Observes
@Inbound MyMsg ev) {
… }
Payara Micro Event Bus
- events triggered on all nodes
- Asynchronous micro services
- No need for service registry
- On top of CDI events
JCache API
• Standard Java API for caching
• Distributed cache
Simple messaging and caching
@OMihalyi
Dynamic scaling
• Just run repeatedly
• binds to a free port to avoid port collisions
• All instances autoconnect to a cluster
− Even across network (multicast)
java -jar payara-micro.jar
--deploy app.war
--autoBindHttp
@OMihalyi
Live Demo
• Enhancements to the Cargo Tracker app using Payara
Micro features
@OMihalyi
• Fully reactive comes at a greater cost
− Dealing with threads, hard to track origin,
communication overhead
• Don’t over-engineer, but leave doors open
• Java EE enables gradual improvement
General advice
@OMihalyi
Questions?
Thank you

More Related Content

What's hot

Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Haim Yadid
 
Node.js Patterns and Opinions
Node.js Patterns and OpinionsNode.js Patterns and Opinions
Node.js Patterns and OpinionsIsaacSchlueter
 
Asynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with CoroutinesAsynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with CoroutinesTobias Schürg
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !Knoldus Inc.
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleZabbix
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Sylvain Zimmer
 
Introduction to Laravel
Introduction to LaravelIntroduction to Laravel
Introduction to LaravelVin Lim
 
Custom coded projects
Custom coded projectsCustom coded projects
Custom coded projectsMarko Heijnen
 
Shootout! Template engines for the JVM
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVMJeroen Reijn
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!Andrew Conner
 
Power Cli Workshop London Vmug
Power Cli Workshop London VmugPower Cli Workshop London Vmug
Power Cli Workshop London Vmugjonathanmedd
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineShawn Hooper
 
Play concurrency
Play concurrencyPlay concurrency
Play concurrencyJustin Long
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
They why behind php frameworks
They why behind php frameworksThey why behind php frameworks
They why behind php frameworksKirk Madera
 
NZIFF and Fastly
NZIFF and FastlyNZIFF and Fastly
NZIFF and Fastlykarlvr
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache CamelKenneth Peeples
 

What's hot (20)

Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions
 
Node.js Patterns and Opinions
Node.js Patterns and OpinionsNode.js Patterns and Opinions
Node.js Patterns and Opinions
 
Asynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with CoroutinesAsynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with Coroutines
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !
 
SSDs are Awesome
SSDs are AwesomeSSDs are Awesome
SSDs are Awesome
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
 
Introduction to Laravel
Introduction to LaravelIntroduction to Laravel
Introduction to Laravel
 
Custom coded projects
Custom coded projectsCustom coded projects
Custom coded projects
 
Shootout! Template engines for the JVM
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVM
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
 
Power Cli Workshop London Vmug
Power Cli Workshop London VmugPower Cli Workshop London Vmug
Power Cli Workshop London Vmug
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command Line
 
Play concurrency
Play concurrencyPlay concurrency
Play concurrency
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
They why behind php frameworks
They why behind php frameworksThey why behind php frameworks
They why behind php frameworks
 
NZIFF and Fastly
NZIFF and FastlyNZIFF and Fastly
NZIFF and Fastly
 
Campus days 2014 owin
Campus days 2014 owinCampus days 2014 owin
Campus days 2014 owin
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache Camel
 
ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817
 

Viewers also liked

Ird filtres et équations
Ird filtres et équations Ird filtres et équations
Ird filtres et équations Françoise Grave
 
Présentation G. Gault TNS Sofrès
Présentation G. Gault TNS SofrèsPrésentation G. Gault TNS Sofrès
Présentation G. Gault TNS SofrèsUEfrance
 
Trabajo final integrador
Trabajo final integrador Trabajo final integrador
Trabajo final integrador saladaniela
 
Melhore o Desenvolvimento do Time com DevOps na Nuvem
Melhore o Desenvolvimento do Time com DevOps na NuvemMelhore o Desenvolvimento do Time com DevOps na Nuvem
Melhore o Desenvolvimento do Time com DevOps na NuvemBruno Borges
 
Automated Integration Testing in Java using Arquillian
Automated Integration Testing in Java using ArquillianAutomated Integration Testing in Java using Arquillian
Automated Integration Testing in Java using ArquillianTommy Tynjä
 
Digitalpreservation 120203055519-phpapp02
Digitalpreservation 120203055519-phpapp02Digitalpreservation 120203055519-phpapp02
Digitalpreservation 120203055519-phpapp02umeshlis
 
Glass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldGlass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldPayara
 
JMS-Java Message Service
JMS-Java Message ServiceJMS-Java Message Service
JMS-Java Message ServiceKasun Madusanke
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Ryan Cuprak
 
Narrazione e mappatura dei bisogni di salute
Narrazione e mappatura dei bisogni di saluteNarrazione e mappatura dei bisogni di salute
Narrazione e mappatura dei bisogni di saluteamandadrafe
 

Viewers also liked (16)

Ird filtres et équations
Ird filtres et équations Ird filtres et équations
Ird filtres et équations
 
Présentation G. Gault TNS Sofrès
Présentation G. Gault TNS SofrèsPrésentation G. Gault TNS Sofrès
Présentation G. Gault TNS Sofrès
 
Здоровье и питание
Здоровье и питаниеЗдоровье и питание
Здоровье и питание
 
Algoritmo ciclico
Algoritmo ciclicoAlgoritmo ciclico
Algoritmo ciclico
 
Trabajo final integrador
Trabajo final integrador Trabajo final integrador
Trabajo final integrador
 
Веки глаза
Веки глазаВеки глаза
Веки глаза
 
Vozrastne osobennosti detey_5-6_let
Vozrastne osobennosti detey_5-6_letVozrastne osobennosti detey_5-6_let
Vozrastne osobennosti detey_5-6_let
 
Melhore o Desenvolvimento do Time com DevOps na Nuvem
Melhore o Desenvolvimento do Time com DevOps na NuvemMelhore o Desenvolvimento do Time com DevOps na Nuvem
Melhore o Desenvolvimento do Time com DevOps na Nuvem
 
Automated Integration Testing in Java using Arquillian
Automated Integration Testing in Java using ArquillianAutomated Integration Testing in Java using Arquillian
Automated Integration Testing in Java using Arquillian
 
Digitalpreservation 120203055519-phpapp02
Digitalpreservation 120203055519-phpapp02Digitalpreservation 120203055519-phpapp02
Digitalpreservation 120203055519-phpapp02
 
Glass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldGlass fish performance tuning tips from the field
Glass fish performance tuning tips from the field
 
Veille district
Veille districtVeille district
Veille district
 
JMS-Java Message Service
JMS-Java Message ServiceJMS-Java Message Service
JMS-Java Message Service
 
Ejercicios propuesto lumen
Ejercicios propuesto lumen Ejercicios propuesto lumen
Ejercicios propuesto lumen
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]
 
Narrazione e mappatura dei bisogni di salute
Narrazione e mappatura dei bisogni di saluteNarrazione e mappatura dei bisogni di salute
Narrazione e mappatura dei bisogni di salute
 

Similar to How to bake reactive behavior into your Java EE applications

JDD 2016 - Ondrej Mihalyi - How to bake reactive behavior into your Java EE ...
JDD 2016 - Ondrej Mihalyi -  How to bake reactive behavior into your Java EE ...JDD 2016 - Ondrej Mihalyi -  How to bake reactive behavior into your Java EE ...
JDD 2016 - Ondrej Mihalyi - How to bake reactive behavior into your Java EE ...PROIDEA
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsOndrej Mihályi
 
How to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsHow to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsOndrej Mihályi
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Introduction to Django-Celery and Supervisor
Introduction to Django-Celery and SupervisorIntroduction to Django-Celery and Supervisor
Introduction to Django-Celery and SupervisorSuresh Kumar
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Baruch Sadogursky
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage SystemsSATOSHI TAGOMORI
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9Ivan Krylov
 
Introducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorIntroducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorFlink Forward
 
Netty - anfix tech&beers
Netty - anfix tech&beersNetty - anfix tech&beers
Netty - anfix tech&beersjorgecarabias
 
Parallel programming
Parallel programmingParallel programming
Parallel programmingSwain Loda
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfKrystian Zybała
 
Speed up large-scale ML/DL offline inference job with Alluxio
Speed up large-scale ML/DL offline inference job with AlluxioSpeed up large-scale ML/DL offline inference job with Alluxio
Speed up large-scale ML/DL offline inference job with AlluxioAlluxio, Inc.
 
A look at FastCgi & Mod_PHP architecture
A look at FastCgi & Mod_PHP architectureA look at FastCgi & Mod_PHP architecture
A look at FastCgi & Mod_PHP architectureAimee Maree Forsstrom
 
Workflow Engines for Hadoop
Workflow Engines for HadoopWorkflow Engines for Hadoop
Workflow Engines for HadoopJoe Crobak
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaMax Alexejev
 

Similar to How to bake reactive behavior into your Java EE applications (20)

JDD 2016 - Ondrej Mihalyi - How to bake reactive behavior into your Java EE ...
JDD 2016 - Ondrej Mihalyi -  How to bake reactive behavior into your Java EE ...JDD 2016 - Ondrej Mihalyi -  How to bake reactive behavior into your Java EE ...
JDD 2016 - Ondrej Mihalyi - How to bake reactive behavior into your Java EE ...
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
How to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsHow to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applications
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Introduction to Django-Celery and Supervisor
Introduction to Django-Celery and SupervisorIntroduction to Django-Celery and Supervisor
Introduction to Django-Celery and Supervisor
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Introducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorIntroducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes Operator
 
Netty - anfix tech&beers
Netty - anfix tech&beersNetty - anfix tech&beers
Netty - anfix tech&beers
 
Parallel programming
Parallel programmingParallel programming
Parallel programming
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Speed up large-scale ML/DL offline inference job with Alluxio
Speed up large-scale ML/DL offline inference job with AlluxioSpeed up large-scale ML/DL offline inference job with Alluxio
Speed up large-scale ML/DL offline inference job with Alluxio
 
A look at FastCgi & Mod_PHP architecture
A look at FastCgi & Mod_PHP architectureA look at FastCgi & Mod_PHP architecture
A look at FastCgi & Mod_PHP architecture
 
Workflow Engines for Hadoop
Workflow Engines for HadoopWorkflow Engines for Hadoop
Workflow Engines for Hadoop
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and Scala
 

More from Ondrej Mihályi

Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsOndrej Mihályi
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroOndrej Mihályi
 
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...Ondrej Mihályi
 
Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsOndrej Mihályi
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactionsOndrej Mihályi
 
Maven in Java EE project
Maven in Java EE projectMaven in Java EE project
Maven in Java EE projectOndrej Mihályi
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 

More from Ondrej Mihályi (8)

Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data grids
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
 
Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data grids
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactions
 
Working with jpa
Working with jpaWorking with jpa
Working with jpa
 
Maven in Java EE project
Maven in Java EE projectMaven in Java EE project
Maven in Java EE project
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 

Recently uploaded

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

How to bake reactive behavior into your Java EE applications

Editor's Notes

  1. -ondrej -mert
  2. Since application requirements changed in recent years, we went through from having tens of servers and gigabytes of data to thousands of multi processors and petabytes of data. We now want applications to be more flexible, loosely coupled from each other and scale at any factor. The idea behind the reactive manifesto is to suffice those needs, by having response, elastic, resilient, message driven applications. Reactive means system will response in a timely manner, which will increase the usability of the application. With the help of asynchronous implementation models, the user could get partial responses and the executed code parts would not block each other for the sake of the responsiveness. It also states that the application will be resilient, meaning that application will stay responsive if any problem occurs. In order to be responsiveness, meaning that to get back to the user faster at every request, application should be elastic, it should increase or decrease its resources according to the input. That would also be the cost-effective way for implementing reactive approach. For having loosely coupled components, reactive systems favor message driven approach, which will allow non-blocking communication between the components. Of course application do not inherently like this, since there is a good deal of traditional blocking API and they are being heavily used inside applications, such as JDBC. And monolithic architectures need to evolve in order to support reactive approach and that means time + money. It’s also hard to do reactive coding, you will be dealing with callbacks and threads spawning everywhere. There are frameworks of course that embodies reactive approach from ground up but they are completely new frameworks like Vert.x, as a Java EE developer you should learn everything from scratch. So in JavaEE wise, we’ll be talking about where you can introduce reactive approach into your existing code base, where it adds the most value. For that reason, we converter the famous cargo-tracker application, into reactive cargo-tracker ;)
  3. When dealing with incoming requests, the traditional approach is – one thread per request, all is sequential, waiting for slow resources like DB or external services adds to the request processing time.
  4. Just a transition slide to next slide – next slide automatically appears after 10 seconds.
  5. But waiting is not bad, if we can afford it. It is simple, as sequential is easier than parallel, and it is thread-safe. And we can afford it in many scenarios. Thus additional complexity to solve blocking calls is not required in many cases.
  6. At this point – a warning finger is raised with But…, and a small pause to watch the video. If there are too many slow blocking calls involved, often many resources (threads, CPU) are being wasted during waiting.
  7. And what if all threads are waiting? You may guess – the system is far from being responsive. The application may halt processing new requests and even crash under high load. Being responsive is one of the key aspects of the Reactive Manifesto, and if our application fails to meet that too often, it becomes unusable and therefore not suitable for production. So let’s look at how the responsiveness can be improved.
  8. How we can improve on this? Let’s introduce more threads, so that we can continue processing something else in the original thread while waiting. `Future`API supports this concept in Java. We gained more control over waiting. Now, we can decide not to wait for a result after timeout and release resources with an error response. But users don’t like error messages, do they?
  9. There are also technically drawbacks to this approach. The API may become complex, requiring checking for results iteratively, or falling back to waiting infinitely once further processing depends on the result. It is also not efficient to resources. It even consumes more threads now, just to give us more control over waiting.
  10. If we let any thread to finish the response, there’s no need to wait for threads to finish. We may simply release threads as the work is finished, and the task that finishes last will complete the request. We only need to pass the context of the request between threads. But since the blocking call is still involved, there is always at least one thread being blocked by it. We need still need to add something more to the recipe to utilize resources effectively.
  11. Ideally, we should not block any thread while waiting for a resource. We only need to handle the response from the resource in another thread. The catch is that the API to access the resource must provide a non-blocking call, which accepts a callback. So the recipe for making the application responsive and resource efficient is: - ability to transfer the request context to another thread - asynchronous API to avoid blocking And the question is – how Java EE supports these 2 concepts?
  12. Java EE supports passing of a request context and finishing the response in another thread: - Servlet - JAX-RS endpoint For example, Servlet IO and JAX-RS client API provide asynchronous calls with callbacks when a response from a resource is ready. But the truth is that this is not possible with every Java EE API. In that case, you need to resort to wrapping a blocking call in a separate thread. But keep in mind that you should get it from a separate thread pool so that it does not affect other processing while being blocked. Async EJB calls provide a simple way to run tasks in separate threads. Managed executors are exactly what you need for a finer-grained control over scheduling tasks in separate threads, even in various thread pools. Finally, WebSockets are convenient to build highly responsive frontends, which are updated as soon as possible and not only after all the data is available.
  13. The JAX-RS 2.0 specification has added asynchronous HTTP support via two classes. The @Suspended annotation, and AsyncResponse interface. Having AsyncResponse instance passed as a parameter to the method states that the HTTP request/response should be detached from the currently executing thread and that the current thread should not try to automatically process the response. AsyncResponse is a callback object, meaning that calling resume method will cause a response to be sent back to the client and will also terminate the HTTP request.
  14. For the client side it’s also possible to introduce async calls, with the help of .async() method invocation and the instance of InvocationCallback that we are providing enables the way to interfere with the server response. Here InvocationCallback is a callback implementation as you would guess, which offers methods named: completed() and failed().
  15. Where Java EE provides the means, Java 8 makes it easier to write reactive code, mainly with 2 new additions - lambdas, which make it very easy to build callbacks - CompletableFuture, which makes it easy to handle asynchronous calls and chain callbacks But how to combine them effectively, as Java EE is built on top of Java 7 only? Ideally, CF or its interface counterpart CompletionStage could be used instead of Future. But that would require support in Java EE, no sooner than in Java EE 8. Therefore we need to adopt another approach. We need to create a CF ourselves and pass it to an asynchronous call, either within the callback object, or as a parameter to an asynchronous EJB method. The asynchronous call will then call either cf.complete() or cf.completeExceptionally() after the call is finished.
  16. Why is CF so much better than Future? Chain of callbacks executable in various threads, instead of just waiting for a thread to complete. It is possible to chain CF themselves using thenCompose, making it easy to chain multiple asynchronous calls. Furthermore provides a standard way to complete the future or throw and exception.
  17. We usually want to access the same resources during request processing. A request spans multiple threads and this causes some problems with the traditional Java EE. References to resources are bound to a thread and have to be transferred to subsequent threads. When new threads are provided using the managed executor service, it automatically passes the context to the new threads. If threads are created using plain Java SE, they context needs to be transferred manually, using the ContextService. In a simple scenario, we can easily wrap a lambda within a contextual proxy using appropriate functional reference. The proxy will then transfer the thread context before each method call. Remember, the contextual proxy has to be created in a managed thread. Its methods can be called in unmanaged threads. It would not work if we created the proxy inside a callback.
  18. -ondrej -mert
  19. -ondrej There’s more to being reactive than just responsiveness. We can continue to extend our analogy with the Kung-fu master to explain the other 3 concepts. - we need to be resilient to problems and any damage received from our enemies and keep fighting -&amp;gt; Resilience - when fighting together with our allies, we shout for help but cannot afford to wait for it and need to continue fighting. The help will come eventually. -&amp;gt; hence Messaging for communication - and of course Elasticity – it would be great if we could clone ourselves to fight more enemies, wouldn’t it? Java EE traditionally offers means to ensure resilience using transactions and clustering; and provide messaging, mainly by the JMS. In a bigger picture, It is usually extend by additional infrastructure to improve resilience and elasticity, e.g. by load balancing and service discovery. But this is not enough. We often need to resort to additional features of a specific application server to complete what is missing. An example of an application server providing more support for building and running reactive applications, is Payara Micro.
  20. So Payara Micro enables you to run war files from the command line without any application server installation. It is small, around 70mb and you can just execute it by using java –jar. You can deploy a web application archive through the command line and with the hazelcast integration each Payara Micro instance that will be spawned will automagically cluster with other Payara Micro processes on the network, giving you an automatic and elastic clustering configuration. If you haven’t tried our Micro before, give it a try we have a good deal of resources on payara.fish, you can even execute Micro on your Raspberry PI…!
  21. So dispatching events across JVM is simple as using CDI’s outbound event mechanism where you wrap your instance type with Event and then fire it in order to have it observed in the handle method given below. One thing to be noted here is: this model executes as the topic approach of JMS. So Event Bus of Payara Micro handles the events on any distributed node, which brings asynchronous model to the implementation. Yay! We have reactive micro services now right? There is no need for an UDDI / Service Registry definition and these all can be implemented with the help of 2 qualifiers on CDI events, @Outbound and @Inbound. Payara Micro uses Hazelcast’s distributed executor in the background to achieve this.
  22. In order to spawn a new server, just run java –jar payara-micro.jar and with – deploy parameter specify your war application and with –autoBindHttp parameter we will enable the application server to auto-bind to an HTTP port to prevent collisions. All spawned micro instances will auto-connect to a cluster, even across networks.
  23. -ondrej -mert
  24. -ondrej -mert
  25. -ondrej -mert