jakarta-ee - 将事务与可运行程序一起使用

标签 jakarta-ee transactions ejb

我有一个带有此方法的@Singleton ejb 类。事务是在方法体末尾提交的,但我在 myRunnable 线程中有一些其他内容,我希望将其包含在当前事务中。有什么办法可以做到吗?

@PostConstruct
public void init() {
    try {
        // do some other stuff
        managedExecutorService.execute(myRunnable);
    } catch (Exception e) {
        LOG.error("Error when initializing...", e);
    }
}

最佳答案

您的“myRunnable 线程”不能包含在您正在运行的事务中。

您不得使用 java 执行程序服务(EJB 规范 16.2.2)或直接管理线程:

The enterprise bean must not attempt to manage threads. ... These functions are reserved for the EJB container. Allowing the enterprise bean to manage threads would decrease the container’s ability to properly manage the runtime environment.

您必须使用managed executor service随 Java EE 7 引入。

关于交易,文档说:

Tasks are run in managed threads provided by the Java™ EE Product Provider and are run within the application component context that submitted the task. All tasks run without an explicit transaction (they do not enlist in the application component's transaction). If a transaction is required, use a UserTransaction instance. A UserTransaction instance is available in JNDI using the name: "java:comp/UserTransaction" or by requesting an injection of a UserTransaction object using the Resource annotation.

关于jakarta-ee - 将事务与可运行程序一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52667202/

相关文章:

java - 何时在 Java EE 环境中打开/关闭 hibernate session

java - UnexpectedRollbackException 覆盖了我自己的异常

mysql - MVCC 行锁定与教科书事务行为

java - 正确使用带有 Servlet 的有状态 Bean

java - 如何将无状态bean中的entitymanager注入(inject)传递给dao而不使用setter方法

Java RestService 从日志文件写入和读取数据

jakarta-ee - JavaEE & JAX-RS : Resource Class Should Be Declared as Singleton or Stateless?

mongodb - Mongoose.js 事务

java - 了解可嵌入的EJBContainer

java - 我可以在多个环境中使用单个 war 文件吗?我是不是该?