Jboss Java EE容器和ExecutorService [英] Jboss Java EE container and an ExecutorService

查看:180
本文介绍了Jboss Java EE容器和ExecutorService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个独立的java应用程序,它使用ExecutorService来并行处理多个作业。

I have a standalone java app which used the ExecutorService to process a number of jobs in parallel

 ExecutorService es = Executors.newFixedThreadPool(10);



现在我想在EJB bean中重用相同的解决方案,但不确定如何正确初始化ThreadPool,因为我通常离开Java EE容器来控制所有线程资源。我可以只使用相同的代码,还是有一个替代的正确方法来获取一个Jboss托管线程池?

I now want to re-use the same solution within an EJB bean but am unsure how to correctly initialize the ThreadPool, since I'd normally leave the Java EE container to control all thread resources. Can I just use the same code or is there an alternative correct way to get a Jboss managed thread pool?

推荐答案

在您的EJB中这样做是使用ManagedExecutorService,它是并发性Utils API(Java EE7)的一部分。您不应该使用任何作为您的企业代码中的java.util.concurrent的一部分的ExecutorService。

The correct way to do this in your EJB is to use the ManagedExecutorService, which is part of the Concurrency Utils API (Java EE7). You shouldn't be using any ExecutorService that is part of the java.util.concurrent in your enterprise code.

通过使用ManagedExecutorService,您的新线程将被创建和管理

By using the ManagedExecutorService your new thread will be created and managed by the container.

以下示例来自我的网站这里

The following example is taken from my site here.

要使用ManagedExecutorService创建一个新的线程,首先创建一个任务对象可叫。在call()方法中,我们将在一个单独的线程中定义我们想要执行的工作。

To create a new thread using a ManagedExecutorService, first create a task object that implements Callable. Within the call() method we will define the work that we want carried out in a separate thread.

public class ReportTask implements Callable<Report> {

    Logger logger = Logger.getLogger(getClass().getSimpleName());

    public Report call() {
        try {
            Thread.sleep(3000);
        catch (InterruptedException e) {
            logger.log(Level.SEVERE, "Thread interrupted", e);
        }
        return new Report();
    }
}

然后我们需要调用任务到ManagedExecutorService的submit()方法。

Then we need to invoke the task by passing it though to the submit() method of the ManagedExecutorService.

@Stateless
public class ReportBean {

    @Resource
    private ManagedExecutorService executorService;

    public void runReports() {
        ReportTask reportTask = new ReportTask();
        Future<Report> future = executorService.submit(reportTask);
    }
}

这篇关于Jboss Java EE容器和ExecutorService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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