Close

Spring Framework - @Async and @EnableAsync Examples

Spring Framework 

@Async marks a method as a candidate for asynchronous execution

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

public class AsyncExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling async method from thread: %s%n",
Thread.currentThread().getName());
bean.runTask();
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

private static class MyBean {

@Async
public void runTask () {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
}
}
}

Output

calling async method from thread: com.logicbig.example.AsyncExample.main()
Running task thread: SimpleAsyncTaskExecutor-1
INFO: No TaskExecutor bean found for async processing
Original Post




package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

public class AsyncArgAndReturnValueExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
String s = bean.runTask("from main");
System.out.println("call MyBean#runTask() returned");
System.out.println("returned value: " + s);
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

private static class MyBean {

@Async
public String runTask (String message) {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
System.out.printf("message: %s%n", message);
System.out.println("task ends");
return "return value";
}
}
}

Output

calling MyBean#runTask() thread: com.logicbig.example.AsyncArgAndReturnValueExample.main()
call MyBean#runTask() returned
returned value: null
Running task thread: SimpleAsyncTaskExecutor-1
message: from main
task ends
INFO: No TaskExecutor bean found for async processing
Original Post




package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncOverrideDefaultExecutorExample {

public static void main (String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling async method from thread: %s%n",
Thread.currentThread().getName());
bean.runTask();

ConcurrentTaskExecutor exec = context.getBean(ConcurrentTaskExecutor.class);
((ExecutorService) exec.getConcurrentExecutor()).shutdown();
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}

@Bean
public TaskExecutor taskExecutor () {
return new ConcurrentTaskExecutor(
Executors.newFixedThreadPool(3));
}
}

private static class MyBean {

@Async
public void runTask () {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
}
}
}

Output

calling async method from thread: com.logicbig.example.AsyncOverrideDefaultExecutorExample.main()
Running task thread: pool-1-thread-1
Original Post




package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AsyncReturningFutureExample {

public static void main (String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
CompletableFuture<String> r = bean.runTask();
System.out.println("result from task:" + r.get());
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

private static class MyBean {

@Async
public CompletableFuture<String> runTask () {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());

CompletableFuture<String> future = new CompletableFuture<String>() {
@Override
public String get () throws InterruptedException, ExecutionException {
return " task result";
}
};
return future;
}
}
}

Output

calling MyBean#runTask() thread: com.logicbig.example.AsyncReturningFutureExample.main()
Running task thread: SimpleAsyncTaskExecutor-1
result from task: task result
INFO: No TaskExecutor bean found for async processing
Original Post

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

public class AsyncOnClassLevelExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling async method from thread: %s%n",
Thread.currentThread().getName());
bean.runTask1();
bean.runTask2();
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

@Async
private static class MyBean {

public void runTask1 () {
System.out.printf("runTask1 thread: %s%n",
Thread.currentThread().getName());
}

public void runTask2 () {
System.out.printf("runTask2 thread: %s%n",
Thread.currentThread().getName());
}
}
}

Output

calling async method from thread: com.logicbig.example.AsyncOnClassLevelExample.main()
runTask1 thread: SimpleAsyncTaskExecutor-1
runTask2 thread: SimpleAsyncTaskExecutor-2
INFO: No TaskExecutor bean found for async processing
Original Post




package com.logicbig.example;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncConfigurerExample {

public static void main (String[] args) throws ExecutionException, InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
bean.runTask();

ConcurrentTaskExecutor exec =
(ConcurrentTaskExecutor) context.getBean("taskExecutor");
ExecutorService es = (ExecutorService) exec.getConcurrentExecutor();
es.shutdown();
}

@EnableAsync
@Configuration
public static class MyConfig implements AsyncConfigurer {
@Bean
public MyBean myBean () {
return new MyBean();
}

@Bean("taskExecutor")
@Override
public Executor getAsyncExecutor () {
return new ConcurrentTaskExecutor(
Executors.newFixedThreadPool(3));
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler () {
return (throwable, method, objects) ->
System.out.println("-- exception handler -- " + throwable);
}
}

private static class MyBean {

@Async
public void runTask () {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());

throw new RuntimeException("test exception");
}
}
}

Output

calling MyBean#runTask() thread: com.logicbig.example.AsyncConfigurerExample.main()
Running task thread: pool-1-thread-1
-- exception handler -- java.lang.RuntimeException: test exception
INFO: Bean 'asyncConfigurerExample.MyConfig' of type [class com.logicbig.example.AsyncConfigurerExample$MyConfig$$EnhancerBySpringCGLIB$$3281f73c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Original Post




package com.logicbig.example;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncExecutorWithQualifierExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling async method from thread: %s%n",
Thread.currentThread().getName());
bean.runTask();

ThreadPoolTaskExecutor exec = context.getBean(ThreadPoolTaskExecutor.class);
exec.getThreadPoolExecutor().shutdown();
}

@EnableAsync
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}

@Bean
@Qualifier("myExecutor1")
public TaskExecutor taskExecutor2 () {
return new ConcurrentTaskExecutor(
Executors.newFixedThreadPool(3));
}

@Bean
@Qualifier("myExecutor2")
public TaskExecutor taskExecutor () {
return new ThreadPoolTaskExecutor();
}
}

private static class MyBean {

@Async("myExecutor2")
public void runTask () {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
}
}
}

Output

calling async method from thread: com.logicbig.example.AsyncExecutorWithQualifierExample.main()
Running task thread: taskExecutor-1
INFO: Initializing ExecutorService 'taskExecutor'
Original Post




See Also