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

查看:20
本文介绍了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,它是 Concurrency 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 创建新线程,首先创建一个实现 Callable 的任务对象.在 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天全站免登陆