使用ScheduledThreadPoolExecutor时如何处理阻塞任务
我想利用一些轻量级任务管理(例如 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于第一个问题:使用 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.
您是否考虑过使用第三方开源软件? 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.