Rafael Lima
Rafael Lima

Reputation: 3535

Spring @Async method called from within the class

I've an spring component which has some methods as @Async.

I want to create a private method and run @Async but it won't works because spring doesn't help self invocation from withing the bean...

Is there a simple way to allow a specific private method to allos AOP @Async? or is just simpler to get a threadpool and execute manually?

Upvotes: 2

Views: 1125

Answers (2)

Azmisov
Azmisov

Reputation: 7243

You can submit the task to a ThreadPoolTaskExecutor directly.

This is more flexible than injecting the proxy bean into the class itself, as @Yevgeniy suggest. In my opinion, its less confusing to someone looking at your code.

It also avoids the whole issue with the class getting proxied, which can mean you need to use @Getter/@Setter's on the async class methods.

In my experience, there have been too many quirks to @Async to make it worth it, and the actual amount of typing you're saving is minimal.

Example:

var future = executor.submit(() -> myAsyncMethod())

Upvotes: 0

Yevgeniy
Yevgeniy

Reputation: 2694

instead of calling your async method on this, inject the bean and call the method on the bean. here is a example:

public class MyService {
    
    @Lazy
    @Autowired
    private MyService myService;
    
    public void doStuff() throws Exception {
        myService.doStuffAsync();
        System.out.println("doing stuff sync.");
    }
    
    @Async
    public void doStuffAsync() throws Exception {
        TimeUnit.SECONDS.sleep(3);
        System.out.println("doing stuff async.");
    }
}
  • you have to use @Lazy!
  • you have to call myService.doStuffAsync() instead of this.doStuffAsync()

Upvotes: 3

Related Questions