我应该在 Web 服务 (EJB 3.0) 中等待一小段时间(一或两秒)。
我发现了这个关于我的问题的问题,这似乎是 EJB 世界中唯一的合法解决方案,但我仍然找不到如何等待的解决方案。我搜索了很多,但似乎无法使用 EJB 3.0 的工具来实现。
真的吗?或者有解决办法吗?
Waiting 1 or 2 seconds in a thread via Thread.sleep
is just fine and won't hurt the app server. There's little difference between this and doing actual work for 1 or 2 seconds. If we were talking 1 or 2 minutes, that would be of more concern and would merit investigating better options for coordinating communication simply for the fact there are better things to do with your CPU than wait.
The primary motivation for the restrictions in the EJB specification around Threads are really there to prevent people from starting threads or destroying threads (start()
, join()
, stop()
, suspend()
, etc.) or changing the thread's state (setName(String)
, setContextClassLoader(ClassLoader)
, setDaemon(boolean)
, setPriority(int)
, etc.). The key thing to understand is that threads are pooled and reused by the container for efficiency. So anything that would affect the state of the pool (dirtying a thread by changing the thread object itself) or compete with that pool (starting/stopping threads) is a very big no-no. The container will also set state in threads indirectly using ThreadLocal
objects for things such as providing JNDI, Transaction, Security and connection management. This makes starting/stopping your own threads a doubly big no-no.
Sleeping in a thread is simply a waste of your own servers time and resources. Not horrible in very small quantities -- it's your time to waste. Longer times would be of concern.
I would, however, say never call Thread.sleep()
in a transaction. Holding locks and calling sleep
is a big no-no. So make sure you mark this method as @TransactionAttribute(NOT_SUPPORTED)
or similar.
我觉得Thread.sleep(2000)
应该是一个简单的解决方案。为什么你觉得行不通?
如果您想在 EJB 方法中等待,您可以使用著名Thread.sleep
的暂停当前执行线程。
注意:您不应该Thread
在 EJB 中进行管理,休眠是一种管理,因此暂停 EJB 不是一种好的做法。
可能你的要求是一种气味,所以它建议你看看你的设计,如果有什么问题。
EJB 不应该(...)创建或管理线程。
在 EJB/Application 容器中生成自己的线程不是首选,尤其是它们由容器管理。一种方法是使用 framework/WorkManager 来执行与线程相关的操作。
WorkManager 是来自 commonj.work(commonj-twm.jar) 的 API
此外,我认为 EJB 的停止在设计上是不好的,而是您可以通过将功能分为两个操作来控制客户端/服务层的延迟。
Interaction with thread isn't recommended with EJB, it's the responsibility of the container.
As a work-around, you can try creating a timer with createTimer(duration, info)
, where you can pass serializable object, if you have to maintain state or hold necessary information for further execution. You can split your logic into two parts/methods, the second method will be executed after specific interval when prior exits.
Therefore, after definied interval, timeout method will be invoked & you can carry the execution forward with the serialized object, if its needed.