SlideShare a Scribd company logo
1 of 22
Download to read offline
Spring @Async
Dragan Juričić, PBZ
May 2015
Topics
2
 Concept of thread pools
 Servlet 3 async configuration
 Task Execution and Scheduling
 Servlet 3 - asynchronous request processing
 Benefits and downsides
Concept of thread pools
3
Concept of thread pools
 thread per request – server model (Tomcat, Jetty, WAS...)
 simplistic model - create a new thread for each task
 disadvantages of the thread-per-task approach:
 overhead of creating creating and destroying threads
 too many threads cause the system to run out of memory
 thread pools based on work queue offers a solution
 Spring TaskExecutor - abstraction for thread pooling
4
TaskExecutor types
5
pre-built implementations included with the Spring
 SimpleAsyncTaskExecutor - starts up a new thread for each
invocation, support a concurrency limit
 SyncTaskExecutor - implementation doesn't execute
invocations asynchronously, takes place in the calling thread
 ConcurrentTaskExecutor - wrapper for a Java 5
java.util.concurrent.Executor
 ThreadPoolTaskExecutor - exposes the Executor
configuration parameters as bean properties
 WorkManagerTaskExecutor - implements the CommonJ
WorkManager interface - standard across IBM's
Servlet 3 async configuration
6
Servlet 3 async configuration
 Spring web application configuration:
 XML config - update web.xml to version 3.0
 JavaConfig - via WebApplicationInitializer interface
 DispatcherServlet need to have:
 „asyncSupported” flag
 Filter involved in async dispatches:
 „asyncSupported” flag
 ASYNC dispatcher type
7
Spring MVC async configuration
 WebMvcConfigurationSupport – the main class providing
the configuration behind the MVC JavaConfig:
 the default timeout value for async requests
 TaskAsyncExecutor (default is SimpleAsyncTaskExecutor)
protected void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(30*1000L);
configurer.setTaskExecutor(mvcTaskExecutor());
}
protected ThreadPoolTaskExecutor mvcTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setQueueCapacity(100);
executor.setMaxPoolSize(25);
return executor;
}
8
Task Execution and Scheduling
9
 @Async annotation - executing tasks asynchronously
(annotation on a method)
 the caller will return immediately and the actual execution of
the method will occur in a task submitted to TaskExecutor
 methods are required to have a Future<T> return value
@Async
Future<Task> returnSomething(int i) {
// this will be executed asynchronously
return new AsyncResult<Task>(results);
}
Spring wraps call to this method in a Runnable instance and
schedule this Runnable on a task executor
10
Asynchronous invocation in Spring 3.0
Async method return value
 Future<T> is a proxy or a wrapper around an object - container that
holds the potential result
 asynchronous task done - extract result
 Future<T> methods:
 get() - blocks and waits until promised result is available
 isDone() - poll if the result has arrived
 cancel() - attempts to cancel execution of this task
 isCanceled() - returns true if this task was cancelled before it completed normally.
 Concrete implementation AsyncResult - wrap result in AsyncResult
implementing Future<T> interface
11
Exceptions with @Async
 Exception that was thrown during the method execution
 @Async method has a Future typed return value - exception will be thrown
when calling get() method on the Future result
 @Async method has void return type - the exception is uncaught and
cannot be transmitted
 void return type - AsyncUncaughtExceptionHandler can be provided
to handle such exceptions
12
The @Scheduled Annotation
 TaskScheduler abstraction for scheduling tasks:
 TimerManagerTaskScheduler - delegates to a CommonJ TimerManager
instance
 ThreadPoolTaskScheduler external thread management is not a
requirement (implements Spring’s TaskExecutor)
 @Scheduled annotation – add to a method along with trigger metadata
@Scheduled(fixedDelay=5000)
public void doSomething() {
// something that should execute periodically
}
@Scheduled(cron="* 15 9-17 * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}
13
Servlet 3 - asynchronous request processing
14
Asynchronous request handling
 Spring 3.2 introduced Servlet 3 based asynchronous request processing
 controller method can now return Callable or DeferredResult instance
 Servlet container thread is released and allowed to process other request:
 Callable uses TaskExecutor thread
 DeferredResult uses thread not known to Spring
 Asynchronous request processing:
 Controller returns and Spring MVC starts async processing
 Servlet and all filters exit the request thread, but response remains open
 Other thread will complete processing and „dispetch” request back to
Servlet
 Servlet is invocked again and processing resumes with async result
15
Callable – an example controller method
@RequestMapping(value = {"callable.html"}, method = RequestMethod.GET)
public Callable<String> callableView(final ModelMap p_model) {
return new Callable<String>() {
@Override
public String call() throws Exception {
//... processing
return „someView";
}
};
}
 WebAsyncTask – wrap Callable for customization:
 timeout
 TaskExecutor
16
DeferredResult – an example controller method
@RequestMapping("/response-body")
@ResponseBody
public DeferredResult<String> quotes() {
DeferredResult<String> deferredResult = new
DeferredResult<String>();
// Save the deferredResult in in-memory queue ...
return deferredResult;
}
// In some other thread...
deferredResult.setResult(data);
17
Exception handling for async requests
 What happens if a Callable or DeferredResult returned from a controller
method raises an Exception?
 Callable
 @ExeceptionHandler method in the same controller
 one of the configured HandlerExceptionResolver instances
 DeferredResult
 calling setErrorResult() method and provide an Exception or any
other Object as result
 @ExeceptionHandler method in the same controller
 one of the configured HandlerExceptionResolver instances
18
Benefits and downsides
19
Benefits
 @Async method:
 asynchronous method calls solves a critical scaling issue
 the longer the task takes and the more tasks are invoked - the more benefit
with making things asynchronous
 Async request:
 decouple processing from Servlet container thread - longer request can
exhaust container thread pool quickly
 processing of AJAX applications efficiently
 browser real-time update – server push (alternative to standard HTTP
request-response approaches: polling, long polling, HTTP streaming)
 Servlet 3 specification:
 asynchronous support
 JavaConfig without need for web.xml and enhancements to servlet API
20
Downsides
21
 threading risks
 additional configuration (servlet, filter, thread pool...)
 asynchronous method calls adds a layer of indirection - no longer dealing
directly with the results, but must instead poll for them
 converting request or method calls to an asynchronous approach may
require extra work
References
 http://spring.io/
 http://oracle.com/
 http://docs.spring.io/spring/docs/current/spring-framework-
reference/html/scheduling.html
 http://www.slideshare.net/bruce.snyder/beyond-horizontal-scalability-concurrency-
and-messaging-using-spring
 http://www.slideshare.net/chintal75/asynchronous-programmingtechniques
 http://www.ibm.com/developerworks/library/j-jtp0730.html
22

More Related Content

What's hot

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
Sri Prasanna
 

What's hot (20)

Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Tech talk
Tech talkTech talk
Tech talk
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 

Similar to JavaCro'15 - Spring @Async - Dragan Juričić

Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror Maker
Simon Suo
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
Sharma Podila
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 

Similar to JavaCro'15 - Spring @Async - Dragan Juričić (20)

Celery
CeleryCelery
Celery
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Fault Tolerance in a High Volume, Distributed System
Fault Tolerance in a  High Volume, Distributed SystemFault Tolerance in a  High Volume, Distributed System
Fault Tolerance in a High Volume, Distributed System
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Concurrency-5.pdf
Concurrency-5.pdfConcurrency-5.pdf
Concurrency-5.pdf
 
Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror Maker
 
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)
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법
 
FlexSC
FlexSCFlexSC
FlexSC
 

More from HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association

Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 

More from HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association (20)

Java cro'21 the best tools for java developers in 2021 - hujak
Java cro'21   the best tools for java developers in 2021 - hujakJava cro'21   the best tools for java developers in 2021 - hujak
Java cro'21 the best tools for java developers in 2021 - hujak
 
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK KeynoteJavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
 
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan LozićJavantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
 
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
 
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
 
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
 
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander RadovanJavantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
 
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
 
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
 
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
 
Javantura v6 - When remote work really works - the secrets behind successful ...
Javantura v6 - When remote work really works - the secrets behind successful ...Javantura v6 - When remote work really works - the secrets behind successful ...
Javantura v6 - When remote work really works - the secrets behind successful ...
 
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej VidakovićJavantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
 
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
 
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
 
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
 
Javantura v6 - How can you improve the quality of your application - Ioannis ...
Javantura v6 - How can you improve the quality of your application - Ioannis ...Javantura v6 - How can you improve the quality of your application - Ioannis ...
Javantura v6 - How can you improve the quality of your application - Ioannis ...
 
Javantura v6 - Just say it v2 - Pavao Varela Petrac
Javantura v6 - Just say it v2 - Pavao Varela PetracJavantura v6 - Just say it v2 - Pavao Varela Petrac
Javantura v6 - Just say it v2 - Pavao Varela Petrac
 
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
Javantura v6 - Automation of web apps testing - Hrvoje RuhekJavantura v6 - Automation of web apps testing - Hrvoje Ruhek
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
 
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
 
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
Javantura v6 - Building IoT Middleware with Microservices - Mario KusekJavantura v6 - Building IoT Middleware with Microservices - Mario Kusek
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

JavaCro'15 - Spring @Async - Dragan Juričić

  • 2. Topics 2  Concept of thread pools  Servlet 3 async configuration  Task Execution and Scheduling  Servlet 3 - asynchronous request processing  Benefits and downsides
  • 4. Concept of thread pools  thread per request – server model (Tomcat, Jetty, WAS...)  simplistic model - create a new thread for each task  disadvantages of the thread-per-task approach:  overhead of creating creating and destroying threads  too many threads cause the system to run out of memory  thread pools based on work queue offers a solution  Spring TaskExecutor - abstraction for thread pooling 4
  • 5. TaskExecutor types 5 pre-built implementations included with the Spring  SimpleAsyncTaskExecutor - starts up a new thread for each invocation, support a concurrency limit  SyncTaskExecutor - implementation doesn't execute invocations asynchronously, takes place in the calling thread  ConcurrentTaskExecutor - wrapper for a Java 5 java.util.concurrent.Executor  ThreadPoolTaskExecutor - exposes the Executor configuration parameters as bean properties  WorkManagerTaskExecutor - implements the CommonJ WorkManager interface - standard across IBM's
  • 6. Servlet 3 async configuration 6
  • 7. Servlet 3 async configuration  Spring web application configuration:  XML config - update web.xml to version 3.0  JavaConfig - via WebApplicationInitializer interface  DispatcherServlet need to have:  „asyncSupported” flag  Filter involved in async dispatches:  „asyncSupported” flag  ASYNC dispatcher type 7
  • 8. Spring MVC async configuration  WebMvcConfigurationSupport – the main class providing the configuration behind the MVC JavaConfig:  the default timeout value for async requests  TaskAsyncExecutor (default is SimpleAsyncTaskExecutor) protected void configureAsyncSupport(AsyncSupportConfigurer configurer) { configurer.setDefaultTimeout(30*1000L); configurer.setTaskExecutor(mvcTaskExecutor()); } protected ThreadPoolTaskExecutor mvcTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setQueueCapacity(100); executor.setMaxPoolSize(25); return executor; } 8
  • 9. Task Execution and Scheduling 9
  • 10.  @Async annotation - executing tasks asynchronously (annotation on a method)  the caller will return immediately and the actual execution of the method will occur in a task submitted to TaskExecutor  methods are required to have a Future<T> return value @Async Future<Task> returnSomething(int i) { // this will be executed asynchronously return new AsyncResult<Task>(results); } Spring wraps call to this method in a Runnable instance and schedule this Runnable on a task executor 10 Asynchronous invocation in Spring 3.0
  • 11. Async method return value  Future<T> is a proxy or a wrapper around an object - container that holds the potential result  asynchronous task done - extract result  Future<T> methods:  get() - blocks and waits until promised result is available  isDone() - poll if the result has arrived  cancel() - attempts to cancel execution of this task  isCanceled() - returns true if this task was cancelled before it completed normally.  Concrete implementation AsyncResult - wrap result in AsyncResult implementing Future<T> interface 11
  • 12. Exceptions with @Async  Exception that was thrown during the method execution  @Async method has a Future typed return value - exception will be thrown when calling get() method on the Future result  @Async method has void return type - the exception is uncaught and cannot be transmitted  void return type - AsyncUncaughtExceptionHandler can be provided to handle such exceptions 12
  • 13. The @Scheduled Annotation  TaskScheduler abstraction for scheduling tasks:  TimerManagerTaskScheduler - delegates to a CommonJ TimerManager instance  ThreadPoolTaskScheduler external thread management is not a requirement (implements Spring’s TaskExecutor)  @Scheduled annotation – add to a method along with trigger metadata @Scheduled(fixedDelay=5000) public void doSomething() { // something that should execute periodically } @Scheduled(cron="* 15 9-17 * * MON-FRI") public void doSomething() { // something that should execute on weekdays only } 13
  • 14. Servlet 3 - asynchronous request processing 14
  • 15. Asynchronous request handling  Spring 3.2 introduced Servlet 3 based asynchronous request processing  controller method can now return Callable or DeferredResult instance  Servlet container thread is released and allowed to process other request:  Callable uses TaskExecutor thread  DeferredResult uses thread not known to Spring  Asynchronous request processing:  Controller returns and Spring MVC starts async processing  Servlet and all filters exit the request thread, but response remains open  Other thread will complete processing and „dispetch” request back to Servlet  Servlet is invocked again and processing resumes with async result 15
  • 16. Callable – an example controller method @RequestMapping(value = {"callable.html"}, method = RequestMethod.GET) public Callable<String> callableView(final ModelMap p_model) { return new Callable<String>() { @Override public String call() throws Exception { //... processing return „someView"; } }; }  WebAsyncTask – wrap Callable for customization:  timeout  TaskExecutor 16
  • 17. DeferredResult – an example controller method @RequestMapping("/response-body") @ResponseBody public DeferredResult<String> quotes() { DeferredResult<String> deferredResult = new DeferredResult<String>(); // Save the deferredResult in in-memory queue ... return deferredResult; } // In some other thread... deferredResult.setResult(data); 17
  • 18. Exception handling for async requests  What happens if a Callable or DeferredResult returned from a controller method raises an Exception?  Callable  @ExeceptionHandler method in the same controller  one of the configured HandlerExceptionResolver instances  DeferredResult  calling setErrorResult() method and provide an Exception or any other Object as result  @ExeceptionHandler method in the same controller  one of the configured HandlerExceptionResolver instances 18
  • 20. Benefits  @Async method:  asynchronous method calls solves a critical scaling issue  the longer the task takes and the more tasks are invoked - the more benefit with making things asynchronous  Async request:  decouple processing from Servlet container thread - longer request can exhaust container thread pool quickly  processing of AJAX applications efficiently  browser real-time update – server push (alternative to standard HTTP request-response approaches: polling, long polling, HTTP streaming)  Servlet 3 specification:  asynchronous support  JavaConfig without need for web.xml and enhancements to servlet API 20
  • 21. Downsides 21  threading risks  additional configuration (servlet, filter, thread pool...)  asynchronous method calls adds a layer of indirection - no longer dealing directly with the results, but must instead poll for them  converting request or method calls to an asynchronous approach may require extra work
  • 22. References  http://spring.io/  http://oracle.com/  http://docs.spring.io/spring/docs/current/spring-framework- reference/html/scheduling.html  http://www.slideshare.net/bruce.snyder/beyond-horizontal-scalability-concurrency- and-messaging-using-spring  http://www.slideshare.net/chintal75/asynchronous-programmingtechniques  http://www.ibm.com/developerworks/library/j-jtp0730.html 22