Spring provides annotation support for asynchronous method execution via @Async and @EnableAsync
package com.logicbig.example; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class MyBean { @Async public void runTask() { System.out.printf("Running task thread: %s%n", Thread.currentThread().getName()); } }
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; import java.util.concurrent.Executors; @EnableAsync @ComponentScan public class AsyncExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncExample.class); MyBean bean = context.getBean(MyBean.class); System.out.printf("calling async method from thread: %s%n", Thread.currentThread().getName()); bean.runTask(); System.out.printf("After calling async method from thread: %s%n", Thread.currentThread().getName()); } }
calling async method from thread: com.logicbig.example.AsyncExample.main()After calling async method from thread: com.logicbig.example.AsyncExample.main()Running task thread: SimpleAsyncTaskExecutor-1
As seen in above output, MyBean#runTask method was run in a separate thread asynchronously.
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.