If Async methods return values, they should return it via an instance of java.util.concurrent.Future
Example
package com.logicbig.example;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Component
public class MyBean {
@Async
public Future<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;
}
}
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@EnableAsync
@ComponentScan
public class AsyncReturningFutureExample {
public static void main (String[] args) throws ExecutionException, InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
AsyncReturningFutureExample.class);
MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
Future<String> r = bean.runTask();
System.out.println("result from task:" + r.get());
}
}
Output
calling MyBean#runTask() thread: com.logicbig.example.AsyncReturningFutureExample.main() Running task thread: SimpleAsyncTaskExecutor-1 result from task: task result
Example Project
Dependencies and Technologies Used:
spring-context 6.2.12 (Spring Context) Version Compatibility: 4.0.0.RELEASE - 6.2.12Version List
×
Version compatibilities of spring-context with this example: