开发者

EJB's and Threading

From what I understand it is illegal to spawn threads from within an EJB as it may potentially interfere with the EJB's lifecycle. However, is it illegal to use predefined Java classes from the JDK which internally spawn an开发者_如何学JAVAd handle threads such as Executor within an EJB, specifically an MDB?


You "cannot" (should not) use threads, thread pools, executors... all of the above. the point of using an app server is to only write business logic and let the app server do the heavy lifting. if you really, really need to do your own threading, use an EJB 3.1 "singleton" service to manage the threading. however, as mentioned by others, it's best to leave this to the app server. one way to do parallel processing in an app server is to use MDBs (which it sounds like you already are using), although depending on the type of parallel processing, these may be too heavyweight.


This is what EJB 3.1 @Asynchronous is for and definitely should be used instead of an Executor. It's generally very dangerous to compete with the container's thread pools. Doing so is a great way to kill performance.

The Asynchronous support will use the container's thread pools and be far safer. See this answer for details on how Asynchronous works.


The biggest issue with threads and EJBs is that threads are a limited resource heavily used by the container, and thread mistakes lead to thread pool leaks that can effectively kill the whole JVM instance.

Executor should be better behaved, but it's still going to use up a thread for some length of time; it also may just fail instantly if someone has tuned the container to use up the available threads.

Summary is that you're going to be tightrope walking.


To add to @Charlie Martin's answer, whatever you need the Executor to do, you could design another EJB to perform the same action without the Executor. This allows the new EJB to run in a separate thread handled by the container. The downside is you might have to "reimplement the wheel" since you still do not want to use threads/Executor from the JVM. It also adds to the overhead of getting one EJB to locate/request/connect/call another.

The bottom line is that EJBs are supposed to be worker threads themselves. It may seem like overkill to replicate code instead of use the Executor and it is up to a point. The biggest distinction is one of scale. Executors will be limited to a single JVM while EJBs can be scaled across JVMs and across servers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜