我已经编写了一段代码来检查Spring框架中的@Async注释行为。
@RequestMapping( value="/async" , method = RequestMethod.GET)
public ModelAndView AsyncCall(HttpServletRequest request)
{
async1();
async2();
return new ModelAndView("firstpage");
}
@Async
private void async1(){
System.out.println("Thread 1 enter");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 1 exit");
}
@Async
private void async2(){
System.out.println("Thread 2 enter");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 2 exit");
}此代码的输出如下所示。
Thread 1 enter
Thread 1 exit
Thread 2 enter
Thread 2 exit通过查看此输出,可以看出这两个@Async函数调用本身是同步的。
据我所知,这两个线程是不同的线程,它们本身应该异步运行。
根据spring proxy修改代码后,打印的调用日志类似。
主线程名: http-apr-8080-exec-8
Thread 1 enter
Async-1 Thread Name: neutrinoThreadPoolExecutor-1
Thread 1 exit
Thread 2 enter
Async-2 Thread Name: neutrinoThreadPoolExecutor-1
Thread 2 exit两个异步调用的线程的名称是相同的,但似乎仍然没有呈现异步行为。
发布于 2017-03-23 17:56:28
这就是@Async不适合我的情况
@EnableAsync是missing@Async方法,而不是public@Async注释的方法,是从同一类的另一个方法调用的。可能会绕过异步代理代码,只调用普通方法。发布于 2017-07-06 02:30:53
Spring的@Async注释有两个需要遵循的规则。
异步方法必须应用于异步方法only
public 原因很简单-该方法需要是公共的,这样它才能被代理。自调用不起作用,因为它绕过了代理,直接调用底层方法。
发布于 2017-03-23 15:01:04
你在Spring应用中启用异步了吗?在Spring Boot中,你可以这样做。
@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("GithubLookup-");
executor.initialize();
return executor;
}
}@EnableAsync注释开启了Spring在后台线程池中运行@Async方法的能力。
https://stackoverflow.com/questions/42969178
复制相似问题