使用ScheduledThreadPoolExecutor时如何处理阻塞任务

发布于 2024-10-09 13:57:23 字数 253 浏览 2 评论 0原文

我想利用一些轻量级任务管理(例如 ScheduledThreadPoolExecutor)来定期执行一些可能阻塞的任务(例如,因为等待获取监视器/锁)。 在这种情况下,任务管理应该检测到这种情况,并应该产生另一个阻塞的同类任务/线程。

如何才能实现这一目标?

作为一个奖励问题: ScheduledThreadPoolExecuter 的文档指出“如果任务的任何执行遇到异常,则后续执行将被抑制”。就我而言,我宁愿重新启动失败的任务。有没有办法改变这种行为?

I'd like to utilize some lightweight task management (e.g. ScheduledThreadPoolExecutor) for periodically doing some Tasks which might block (e.g. because of waiting to acquire a monitor/lock).
In such case the task management should detect that situation and should spawn another task/thread of the same kind which blocks.

How can this be achieved?

And as a bonus question:
Documentation of ScheduledThreadPoolExecuter states that "If any execution of the task encounters an exception, subsequent executions are suppressed". In my case I rather would like to restart the task which failed. Is there a way to alter this behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稳稳的幸福 2024-10-16 13:57:23

对于第一个问题:使用 java.util.concurrent.Lock 并调用 tryLock() 并设置超时。如果超时到期(比如 5 秒),则创建一个与当前任务类型相同的新任务,将其传递给执行器,然后返回等待锁,这次是以阻塞方式。

对于第二个问题,我会考虑将计划的作业包含在一个大的 try/catch 块中,以防止意外的异常冒泡到执行程序本身。

For the first question : Use a java.util.concurrent.Lock and call tryLock() with a timeout. If the timeout expires (say, 5 seconds), then create a new task of the same kind as the current, pass it to the executor, and go back waiting for the lock, this time in a blocking way.

For the second question, I would consider enclosing the scheduled job in a big try/catch block to prevent unexpected exceptions to bubble up to the executor itself.

誰認得朕 2024-10-16 13:57:23

您是否考虑过使用第三方开源软件? Quartz调度器(http://www.quartz-scheduler.org/)非常灵活,值得尝试。

Have you thought of using 3rd party open source software? The Quartz scheduler (http://www.quartz-scheduler.org/) is very flexible and is worth to try.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文