<div dir="ltr" style="text-align: left;">
<div style="font-family: calibri, sans-serif; text-align: justify;">
<div style="font-size: 13pt;">In this tutorial, we will discuss the asynchronous execution support in Spring and the @Async annotation. There are cases in which it is necessary to execute pieces of code asynchronous. An example is the sending of a (JMS) message from your system to another system. The advantage is that the user does not have to wait in the front-end while the message is being sent. Another example of possible asynchronous execution is the case where messages have a clear ordering.</p>
<div id="ads-id" align="center"></div>
<p>Annotating a method of a bean with <b>@Async </b>will make it execute in a separate thread i.e. the caller will not wait for the completion of the called method.</p>
<p><b>Enable Async Support</b><br />
The <b>@EnableAsync</b> annotation switches on Spring’s ability to run @Async methods in a background thread pool. For Enabling asynchronous processing with Java configuration got by simply adding the @EnableAsync to a configuration class:</p>
<pre class="highlight">@Configuration
@EnableAsync
public class SpringAsyncConfig { ... }
</pre>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><b>Popular Tutorials</b></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/2012/06/spring-30-baby-step-to-learn.html"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/spring-web-mvc-framework-chapter-38.html"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/2016/06/introduction-to-spring-boot-a-spring-boot-complete-guide.html"><em><strong>Spring Boot Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/2013/02/spring-security-take-baby-step-to-secure.html"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint.html"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/using-spring-jdbc-framework-chapter-32.html"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/2017/01/spring-hateoas-hypermedia-driven-restful-web-service.html"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/2017/01/microservices-with-spring-boot.html"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/2013/06/jax-rs-web-service-tutorial.html"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/2013/01/core-java-baby-step-to-be-best-java-ian.html"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/2012/03/hibernate-3-on-baby-steps.html"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/spring-batch-process-with-example.html"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<p>Asynchronous processing can also be enabled using XML configuration – by using the task namespace:</p>
<pre class="highlight"><;task:executor id="myexecutor" pool-size="5" />;
<;task:annotation-driven executor="myexecutor"/>;
</pre>
<p><b><br />
Limitations for @Async</b></p>
<ol>
<li>it must be applied to public methods only</li>
<li>self invocation – calling the async method from within the same class – won’t work</li>
</ol>
<p>The reasons are simple – the method needs to be public so that it can be proxied. And self-invocation doesn’t work because it bypasses the proxy and calls the underlying method directly.</p>
<p><b>The @Async Annotation</b><br />
Annotation that marks a method as a candidate for asynchronous execution. Can also be used at the type level, in which case all of the type&#8217;s methods are considered as asynchronous.</p>
<p><b>1. Methods with void Return Type</b><br />
Following is the simple way to configure a method with void return type to run asynchronously:</p>
<pre class="highlight">@Async
public void asyncMethodWithVoidReturnType() {
 System.out.println("Execute method asynchronously. "
 + Thread.currentThread().getName());
}
</pre>
<p><b>2. Methods With Return Type</b><br />
@Async can also be applied to a method with return type – by wrapping the actual return in a <b>Future</b>:</p>
<pre class="highlight">@Service
public class GitHubLookupService {

 RestTemplate restTemplate = new RestTemplate();

 @Async
 public Future<;User>; findUser(String user) throws InterruptedException {
 System.out.println("Looking up " + user);
 User results = restTemplate.getForObject("https://api.github.com/users/" + user, User.class);
 // Artificial delay of 1s for demonstration purposes
 Thread.sleep(1000L);
 return new AsyncResult<;User>;(results);
 }

}
</pre>
<p>Spring also provides an <b>AsyncResult </b>class which implements Future. This can be used to track the result of the asynchronous method execution.</p>
<p>Now, let’s invoke the above method and retrieve the result of the asynchronous process using the <b>Future</b> object</p>
<pre class="highlight">public void testAsyncAnnotationForMethodsWithReturnType()
 throws InterruptedException, ExecutionException {
 System.out.println("Invoking an asynchronous method. "
 + Thread.currentThread().getName());
 Future<;User>; future = GitHubLookupService.findUser(user);
 
 while (true) {
 if (future.isDone()) {
 System.out.println("Result from asynchronous process - " + future.get());
 break;
 }
 System.out.println("Continue doing something else. ");
 Thread.sleep(1000);
 }
}
</pre>
<p><b>The Executor</b><br />
By default, Spring uses a <b>SimpleAsyncTaskExecutor </b>to actually run these methods asynchronously. The defaults can be overridden at two levels – at the application level or at the individual method level.<br />
<b>1. Override the Executor at the Method Level</b></p>
<pre class="highlight">@Configuration
@EnableAsync
public class SpringAsyncConfig {
 
 @Bean(name = "threadPoolTaskExecutor")
 public Executor threadPoolTaskExecutor() {
 return new ThreadPoolTaskExecutor();
 }
}
</pre>
<p>Then the executor name should be provided as an attribute in @Async:</p>
<pre class="highlight">@Async("threadPoolTaskExecutor")
public void asyncMethodWithConfiguredExecutor() {
 System.out.println("Execute method with configured executor - "
 + Thread.currentThread().getName());
}
</pre>
<p><b>2. Override the Executor at the Application Level<br />
</b></p>
<pre class="highlight">@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
 
 @Override
 public Executor getAsyncExecutor() {
 return new ThreadPoolTaskExecutor();
 }
 
}
</pre>
<p>The configuration class should implement the AsyncConfigurer interface – which will mean that it has the implement the getAsyncExecutor() method. It’s here that we will return the executor for the entire application – this now becomes the default executor to run methods annotated with @Async.</p>
<p><b>Exception Handling</b><br />
We’ll create a custom async exception handler by implementing AsyncUncaughtExceptionHandler interface. The handleUncaughtException() method is invoked when there are any uncaught asynchronous exceptions:</p>
<pre class="highlight">public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
 
 @Override
 public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
 System.out.println("Exception message - " + throwable.getMessage());
 System.out.println("Method name - " + method.getName());
 for (Object param : obj) {
 System.out.println("Parameter value - " + param);
 }
 }
 
}
</pre>
<p>When a method return type is a Future, exception handling is easy – Future.get() method will throw the exception.</p>
<p>But, if the return type is void, exceptions will not be propagated to the calling thread. Hence we need to add extra configurations to handle exceptions.</p>
<p>we also need to override the getAsyncUncaughtExceptionHandler() method to return our custom asynchronous exception handler:</p>
<pre class="highlight">@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
 return new CustomAsyncExceptionHandler();
}
</pre>
<p><b>Summary:</b><br />
Congratulations! You’ve learned an asynchronous service. And also we have seen how to enable async call in spring framework.</p>
<p>Happy Spring Learning.</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px;"><b>Spring Related Topics you may like</b></p>
<ol style="text-align: left;">
<li><b><a href="https://dineshonjava.com/2012/10/interview-questions-on-spring.html">Spring Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-interview-questions-and-answers.html">Spring AOP Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/02/spring-mvc-interview-questions-and-answers.html">Spring MVC Interview Questions</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/02/spring-security-interview-questions-and-answers.html">Spring Security Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-rest-web-services-interview-questions-and-answers.html">Spring REST Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/04/spring-boot-interview-questions-and-answers.html">Spring Boot Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/04/spring-boot-microservices-interview-questions-answers.html">Spring Boot Microservices Interview Questions and Answers</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/dependency-injection-in-spring.html">Dependency Injection (DI) in Spring </a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/spring-ioc-container.html">Spring IoC Container</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/what-is-bean-factory-in-spring.html">What is Bean Factory in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/application-context-in-spring.html">ApplicationContext in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/bean-autowiring-in-spring.html">Bean Autowiring in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/understanding-bean-scopes.html">Spring Bean Scopes</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/create-custom-bean-scope-in-spring-example.html">Create Custom Bean Scope in Spring Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/06/using-applicationcontextaware-in-spring.html">Using ApplicationContextAware in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/bean-lifecycle-and-callbacks.html">Spring Bean Life Cycle and Callbacks</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/writing-beanpostprocessor-in-spring.html">BeanPostProcessor in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/writing-beanfactorypostprocessor-in.html">BeanFactoryPostProcessor in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/annotations-in-spring-and-based.html"> Annotations in Spring and Based Configuration</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/spring-jsr-250-annotations.html">Spring JSR-250 Annotations</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/01/jsr-330-annotations-in-spring.html">JSR 330 Annotations in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/stereotype-annotations-in-spring.html">Spring @Component, @Repository, @Service and @Controller Stereotype Annotations</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/01/method-injection-with-spring-using-lookup-method-property.html">Method injection with Spring using Lookup method property</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/introduction-to-aop-in-spring.html">Spring AOP-Introduction to Aspect Oriented Programming</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/07/spring-aspect-annotation.html">@Aspect Annotation in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-aspectj-before-annotation-advice-example.html"> Spring AOP AspectJ @Before Annotation Advice Example<br />
</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-before-advice-example-using-xml-config.html"> Spring AOP Before Advice Example using XML Config</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-aspectj-after-annotation-advice-example.html"> Spring AOP AspectJ @After Annotation Advice Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-after-advice-example-using-xml-config.html"> Spring AOP After Advice Example using XML Config</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-aspectj-after-returning-annotation-advice-example.html"> Spring AOP AspectJ @AfterReturning Annotation Advice Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-after-returning-advice-example-using-xml-config.html"> Spring AOP After-Returning Advice Example using XML Config</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-aspectj-after-throwing-annotation-advice-example.html"> Spring AOP AspectJ @AfterThrowing Annotation Advice Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-after-throwing-advice-example-using-xml-config.html"> Spring AOP After Throwing Advice Example using XML Config</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-aspectj-around-annotation-advice-example.html"> Spring AOP AspectJ @Around Annotation Advice Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-around-advice-example-using-xml-config.html"> Spring AOP Around Advice Example using XML Config</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/understanding-aop-proxies-chapter-31.html">Spring AOP Proxies in Spring</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/spring-aop-transaction-management-in.html"> Spring AOP Transaction Management in Hibernate</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/transaction-management-in-spring.html">Spring Transaction Management</a></b></li>
<li><b><a href="https://dineshonjava.com/2012/12/declarative-transaction-management.html">Spring Declarative Transaction Management Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/03/spring-aop-ordering-of-aspects-with-example.html">Spring AOP-Ordering of Aspects with Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/02/spring-security-java-based-configuration-with-example.html">Spring Security Java Based Configuration with Example</a></b></li>
<li><b><a href="https://dineshonjava.com/2017/02/spring-security-xml-namespace-configuration-example.html">Spring Security XML Namespace Configuration Example</a></b></li>
</ol>
</div>
</div>
</div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-cache-tutorial/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/what-is-interface-and-what-are-the-advantages-of-making-use-of-them-in-java/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '126'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…