Can I use an EJB in an infinite thread

时间:2015-07-29 00:14:11

标签: jsf java-ee ejb

I would like to know if it's prohibited to use an EJB in an infinite thread(since it can't be given back to the container).

Something like this:

<>

And the thread:

@ManagedBean(eager = true)
@ApplicationScoped
public class TestListenner {

    private ResultThread result;

    @PostConstruct
    public void init() {
        result = new ResultThread ();
        Thread myThread = new Thread(result);
        myThread.start();
    }
    public ResultThread getResult() {
        return result;
    }
}

I'm working with EJB's since I started working with databases. I went over daofactories and the likes but I forgot about them(it was a year ago). I use them to do actions on my database when an user request a web page on my web app. But now I need to have a thread that calculate things in my database continuously to decrease the response time. If I cannot use EJB for the reason the container needs to have an handle on them, then what should I use ?

Hopefully I can use a class similar to what I'm used to use :

public class ResultThread implements Runnable{
    @EJB
    private SomeService service;
    private boolean continueWork = true;

    public void run(){
        while(continueWork){
            service.doSomething();
            //some proccessing
        }
    }

Edit: The first answer by BalusC in this topic seems to imply that spawning threads in a ManagedBean wouldn't be dangerous in a case where no additional threads could be spawned. Since my bean is ApplicationScoped, which the web-app uses 1 and only 1 instance of it to do background work on the database (I've actually like a TOP 100 "posts" table that needs to be continually recalculated over time so I can query the table -with another bean- to have a fast answer).

2 个答案:

答案 0 :(得分:3)

你现在所取得的成就至少有一个原因:

You can't inject resources into non-managed components。要使@EJB注释起作用,ResultThread应该是托管bean,并由容器注入。这意味着,您必须至少使用CDI来注入它,而不是现在的new ResultThread。什么工作将看起来像:

@Inject
private ResultThread result;

这样,容器就可以进行操作了。

但最重要的是,有更好的方法可以做你想要做的事情。

您可能还有兴趣知道EJB不允许生成自己的线程;事实上,它不赞成在容器中做任何手工穿线。为什么?容器是一个托管环境 - 内存和并发性已经经过深思熟虑和设计。您的手动线程打破了该模型以及容器可能能够为您的bean和其他应用程序组件提供的任何保证

相关:

答案 1 :(得分:1)

您不能在Java EE容器上使用自己的Threads。

http://www.oracle.com/technetwork/java/restrictions-142267.html#threads

Java EE规范为此类工作提供了TimerServices。

https://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html