2

I have a problem with sending email with method annotated as @Async. Firstly, I am not sure if it is possible to work as I want so I need help with explanation.

Here is what am doing now:

In main method i have annotation

@EnableAsync(proxyTargetClass = true) 

Next I have AsyncConfig class

import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurerSupport; import java.util.concurrent.Executor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class AsyncConfig extends AsyncConfigurerSupport { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(2); executor.setQueueCapacity(500); executor.setThreadNamePrefix("email-"); executor.initialize(); return executor; } } 

Of course, its rest application so i have controller, service etc, looks normally, nothing special

My async method looks like this:

 @Async public void sendEmail() throws InterruptedException { log.info("Sleep"); Thread.sleep(10000L); //method code log.info("Done"); } 

I executing this method in another service method:

@Override public boolean sendSystemEmail() { try { this.sendEmail(); } catch (InterruptedException e) { e.printStackTrace(); } log.info("pending sendEmail method"); return true; } 

Now what I want archive is to ignore executing sendEmail() function and execute return true; meanwhile function sendEmail() will be executing in another Thread. Of course it doesn't work now as I want. Unfortunately.

Note that I am new into async programming, so I have lack of knowledge in some parts of this programming method.

Thanks for any help.

1
  • 1
    Ah the classic error/misunderstanding. For async processing spring uses AOP. AOP is applied using proxies, which means only calls INTO the object will get AOP applied. You are doing a method call from inside the proxy. You need to call sendMail externally and not internally. Commented Apr 25, 2017 at 10:03

1 Answer 1

4

First – let’s go over the rules – @Async has two limitations:

it must be applied to public methods only 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.

http://www.baeldung.com/spring-async

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.