开发者

How to deal with blocking Tasks when using ScheduledThreadPoolExecutor

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开发者_C百科 restart the task which failed. Is there a way to alter this behaviour?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜