EJB 中的线程生成库

Thread spawning libraries in EJB

是否允许在生成和管理线程的 EJB 中使用库?

我用 class 编写了一个 JavaSE 库,如下所示:

public class LibraryClass {
    public void longRunningMethod() {
        ExecutorService service = Executors.newFixedThreadPool(10);
        //schedule tasks
        service.shutdown();
        try {
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

EJB 示例:

@Stateless
class Bean {
    public void beanMethod() {
        LibraryClass libraryClass = new LibraryClass();
        libraryClass.longRunningMethod();
    }
}

在 EJB 中使用这样的东西可以吗?

规范指出 "The enterprise bean must not attempt to manage threads",如果线程在 EJB 之外进行管理,这是否仍然适用,甚至可能不受开发人员控制(例如,在使用第 3 方库时)?

您好,总的来说建议是正确的。这是一种不好的做法,因为您已经 运行 在一个 'contained' 环境中,该环境已经为您完成了线程处理/线程池(分配)的繁重工作。如果你真的想跨线程,你应该确保容器知道它们或向他提供构造,以便它可以处理和监视它。这是通过在 Java.See here and here

中使用执行器服务实现的