从另一个异步方法称为春异步方法 [英] Spring async method called from another async method

查看:181
本文介绍了从另一个异步方法称为春异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用弹簧4和我注意到一个奇怪的行为......如果我打电话异步方法多次从一个正常的实例方法,然后他们都在不同的线程,终点在随机时间调用。但是,如果我多次调用另一个异步方法异步方法,那么他们完成才能。我有这样的事情:

I'm using Spring 4 and I've noticed an odd behaviour... if I'm calling an async method multiple times from a normal instance method then they are all called in different threads and finish at random times. But if I call multiple times an async method from another async method then they finish in order. I have something like this:

@Async
public void nonAsyncMethod() {
  for (int i = 0; i < 30; i++) {
     asyncMethod();
  }
}

@Async
public void asyncMethod() {
   ... something here
}

我使用的是默认的异步执行者。我应该使用一个不同?然而此执行不重用任何线程,并开始一个又一个,每次所以它应该是罚款...它可以只是一个巧合吗?但我已经试过像10倍以上,如果我恢复到非异步对于第一种方法,然后他们完成随机

I'm using the default async executor. Should I use a different one? However this executor do not reuse any threads and starts another one every time so it should be fine... Can it be just a coincidence? But I've tried like more than 10 times and if I revert back to non-async for the first method then they finish randomly

推荐答案

你所描述的是Spring AOP中的经典陷阱。

What you are describing is a classic pitfall of Spring AOP.

总之,春季能够提供它需要创建为您在运行时类代理异步行为。然后代理为所欲为它需要之前和/或致电code后做。但是,在你的情况,是不是正在申请第二个方法的代理机制。

In short, for Spring to be able to provide the async behavior it needs to create a proxy for your class at runtime. The proxy then does whatever it needs to do before and/or after calling your code. But in your case, the proxy mechanism is not being applied for the second method.

在你的类的一个bean是通过Spring注入到其他一些部件,春天真的注入代理来代替。为此代理的相关方法被调用。然而,当你调用从类中的方法,Spring AOP的局限性意味着代理从来没有进场,而是常规的方法被调用 - 没有额外的功能。

When a bean of your class is injected via Spring into some other component, Spring really injects the proxy instead. Therefor the relevant method of the proxy is called. However, when you are calling a method from inside the class, the limitations of Spring AOP mean the proxy never comes into play, but instead the regular method is called - with no extra features.

这就是为什么 asyncMethod 总是同一个线程中调用它的同班另一种方法上执行。

That is why asyncMethod is always executing on the same thread as the other method in the same class that called it.

查看的优秀博客文章以及<一个href=\"http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-proxying\"相对=nofollow>此内容 Spring文档的一部分。

Check out this excellent blog post as well as this part of Spring documentation.

有解决问题的一些方法(请查看 )不要求你重构你的code,但如果你想异步在这两种方法的工作无论什么时候,做最简单的事情就是重构第二种方法到另一个类。

There are some ways around the problem (check out this) that don't require you to refactor your code, but if you want async to work on both methods no matter what, the simplest thing to do is refactor the second method into another class.

这篇关于从另一个异步方法称为春异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆