我有一个带有此方法的@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/