DevTest28
DevTest28

Reputation: 146

Multithreading in the spring project is not working properly

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

Answers (3)

ACV
ACV

Reputation: 10560

@Async has two limitations:

  1. it must be applied to public methods only
  2. self-invocation – calling the async method from within the same class – won’t work.

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

riorio
riorio

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

Shailendra
Shailendra

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

Related Questions