Reputation: 146
I need to run a function on a complete independent thread wile the rest of my function gets executed for example
public void a(){
// do dome work
}
public void b(){
// do dome work
a()
return "hello"
}
I need my code to start ruining function a but returns hello without waiting for function a to end
I have tried task executors with spring and @Async annotation but noting is working
public static String mainMEthod() {
asyncMethodWithReturnType();
return "hello";
}
@Async
public static Future<String> asyncMethodWithReturnType() {
for (int i = 0; i < 10; i++) {
System.out.println("Execute method asynchronously - " +
Thread.currentThread().getName());
}
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
//do anything
}
return null;
}
Here is the output :
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
but it should not be running on the main thread
Upvotes: 1
Views: 1245
Reputation: 10560
@Async
has two limitations:
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.
Also make sure to configure correctly:
@Configuration
@EnableAsync
public class SpringAsyncConfig { ... }
Read more:
https://www.baeldung.com/spring-async
Upvotes: 4
Reputation: 6836
The @Async
can't be run in a separate thread if the caller is within the same bean.
So option one is to move the a()
method to a different bean and call it from b()
Or, consider doing what we did in our spring boot project when we needed something similar:
public void b() {
CompletableFuture.runAsync(() -> a());
return "hello";
}
Upvotes: 0
Reputation: 9102
The way Spring add functionalities like Async
(apart from many others like this) is by creating and injecting a proxy which has the logic of providing these functionality.
In your case the call to asyncMethodWithReturnType
cannot be intercepted by Spring as this is plain java method call without intermediate spring managed proxy. For more information you can check out here.
Upvotes: 0