CDI多线程 [英] CDI multithreading
问题描述
我们想优化我们的应用程序.正在进行一些线性的工作,可以在具有较小工作集的多个线程中执行.
We want to optimize our application. There is some streight linear work going on, that can be executed in multiple threads with smaller working sets.
从CDI管理的bean中使用@Inject
批注访问我们的典型服务.同样,这样的服务也可以注入自己的依赖项,即:
Our typical service is accessed using the @Inject
annotation from within our CDI-managed beans. Also such a service could have it's own dependencies injected, i.e.:
public class MyService {
@Inject
private OtherService otherService;
@Inject
private DataService1 dataService1;
...
public void doSomething() {
...
}
}
因为我不能在实现Runnable
的类中使用@Inject
. (它不是容器管理的.)我尝试在启动线程之前将所需的服务传递给类.因此,使用类似这样的方法,可使服务实例(myService
)在线程内可用:
Because I can not use @Inject
inside the class implementing Runnable
. (It's not container managed.) I tried to pass the required services to the class before starting the thread. So, using something like this, makes the service instance (myService
) available within the thread:
Class Thread1 implements Runnable{
private MyService myService
public Thread1(MyService myService){
this.myService = myService;
}
public void run(){
myService.doSomething();
}
}
在调用层次结构之后,可以调用doStometing()
,因为已经传递了对myService
的引用.据我了解的CDI,注入是在第一次访问属性时完成的,这意味着,当doStomething()
方法尝试访问otherService
或dataService1
时,将执行注入.
Following the call-hierarchy the call to doStometing()
is fine, because a reference to myService
has been passed. As far as I understand CDI, the injection is done the moment the attribute is accessed for the first time, meaning, when the doStomething()
method tries to access either otherService
or dataService1
, the injection would be performed.
但是到那时我收到一个例外,那就是没有可用的上下文.
At that point however I receive an exception, that there is no context available.
我还尝试使用JBossThreadExecuter
类而不是 Plain-Threads -这会导致完全相同的结果.
I also tried to use the JBossThreadExecuter
class instead of Plain-Threads - it leads to the very same result.
问题是,是否存在将上下文(或请求)与创建的Thread
相关联的好方法?
So the question would be, if there is a nice way to associate a context (or request) with a created Thread
?
对于EJB-Beans,我读到用@Asynchronous
标记方法将导致该方法在托管线程中运行,该线程本身将连接到上下文.那基本上就是我要寻找的.
For EJB-Beans, I read that marking a method with @Asynchronous
will cause the method to be run in a managed thread which itself will be wired to the context. That would basically be exactly what I'm searching for.
有没有办法在CDI中做到这一点?
Is there a way to do this in CDI?
或者有没有办法从非托管线程中获取context
?
Or is there any way to obtain a context
from within a unmanaged thread?
推荐答案
Weld allows programmatic context management, (there's an example in the official docs).
但是在您采用这种方式之前,请给EJB一个机会)
@Async调用功能完全适合您的情况.作为奖励,您将获得超时拦截和事务管理.
But before you go this way give EJBs a chance )
@Async invocation functionality is there exactly for your case. And as a bonus you'll get timeout interception and transaction management.
这篇关于CDI多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!