Spring @ Async Exception Handling and @ async Exception Handling

Source: Internet
Author: User

Spring @ Async Exception Handling and @ async Exception Handling

In the previous two articles, the author introduced common exception handling in Java sub-threads and Exception Handling in Spring web applications. The link is as follows:

Exception Handling in Java subthreads (common)

Exception Handling in Spring web reference

Today, we want to write the Exception Handling Method in the method annotated by Spring @ Async.

 

Generally, if we want to perform a time-consuming operation in the program (such as calling other external modules), it is generally executed asynchronously.

There are two methods:

  • Generate a thread pool ThreadPoolExecutor and submit the task for execution.
  • It is more convenient to use the Spring @ Async annotation to modify the method that requires asynchronous execution.

For exception handling in the first method, the author has introduced in the article "Exception Handling in Java subthreads (general)", that is, to obtain the Future object after submitting the task, through future. get () can capture ExcecutionException when obtaining the return value.

How can I handle exceptions in the Spring @ Async annotation method? The landlord thought of two methods.

Solution 1: Configure AsyncUncaughtExceptionHandler (for methods without return values)

Use AsyncConfigurer to customize thread pools and handle exceptions.

 1 @Configuration 2 @EnableAsync 3 public class SpringAsyncConfiguration implements AsyncConfigurer { 4     private static final Logger logger = LoggerFactory.getLogger(getClass());
5 @Bean 6 @Override 7 public Executor getAsyncExecutor() { 8 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 9 executor.setCorePoolSize(8);10 executor.setMaxPoolSize(16);11 executor.setQueueCapacity(64);12 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());13 executor.setThreadNamePrefix("SpringAsyncThread-");14 15 return executor;16 }17 18 @Override19 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {20 return new SpringAsyncExceptionHandler();21 }22 23 class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {24 @Override25 public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {26 logger.error("Exception occurs in async method", throwable.getMessage());27 }28 }29 30 }
Method 2: capture exceptions through AsyncResult (for methods with return values)

If the asynchronous method has a return value, it should return the object of the AsyncResult class to capture exceptions at the call.

Because AsyncResult is a subclass of the Future interface, you can capture ExcecutionException when obtaining the return value through future. get.

Asynchronous Method:

@ Servicepublic class AsyncService {@ Async public AsyncResult <String> asyncMethodWithResult () {// do something (exception may occur) return new AsyncResult ("hello ");}}

Exceptions caught at the call:

 1 public class Test { 2  3     private Logger logger = LoggerFactory.getLogger(getClass()); 4  5     @Autowired 6     AsyncService asyncService; 7  8     public void test() { 9         try {10             Future future = asyncService.asyncMethodWithResult();11             future.get();12         } catch (ExecutionException e) {13             logger.error("exception occurs", e);14         } catch (InterruptedException e) {15             logger.error("exception occurs", e);16         }17     }18 19 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.