3 回答
TA贡献1836条经验 获得超5个赞
我通过为我的可运行对象扩展 ConcurrentLinkedQueue 并将它们保存在我在 ServletContextListener 的 initialize 方法中实例化的管理器中解决了这个解决方案。通过覆盖 ConcurrentLinkedQueue 的 offer() 方法来持续轮询直到队列为空,我能够同步处理可运行对象。
不幸的是,这会锁定请求线程,直到 runnable 完成,我将不得不让我的用户密切关注它并让我知道页面是否最终运行很长时间,但至少在我的测试环境中,该过程似乎是亚秒即使我一次打 20 个,所以我现在还好。
我仍然更喜欢从我的 Tomcat 容器执行的 ExecutorService 但在请求范围之外,但除非有人可以回答这个问题,否则我现在只好离开它
TA贡献1829条经验 获得超7个赞
“我相信有更好的方法可以做到这一点”
基于此,您需要在调用另一个线程之前创建/查找所有请求和会话范围的组件。实际上,请求注入是线程本地的,无法在您的场景中工作。
TA贡献2021条经验 获得超8个赞
你看起来像那样吗?
@Component 公共类 AsynchronousThread 扩展了 Thread {
public static final Logger LOGGER = LoggerFactory
.getLogger(AsynchronousThread.class);
@Autowired
private Writer writer;
private BlockingQueue<IndexContextDTO> blockingQueue = new LinkedBlockingQueue<IndexContextDTO>(
500);
/**
*
*/
public AsynchronousThread() {
super("AsynchronousThread");
}
@PostConstruct
public void init() {
Integer internalQueueSize = 100;
this.blockingQueue = new LinkedBlockingQueue<>(internalQueueSize);
this.start();
}
@Override
public void run() {
while (true) {
// Do stuff
}
}
public void putInQueue(IndexContextDTO message) {
try {
this.blockingQueue.put(message);
} catch (InterruptedException interruptedException) {
// This exception will be thrown in very rare case.
LOGGER.error("An error while putting message in the queue. "
+ message, interruptedException);
}
}
}
添加回答
举报