如何通知主线程 ScheduledExecutor 任务线程中发生的异常?
我在 ScheduledExecutor< 中有一个任务/code>
定期运行。如果我想将特定的异常归结到主线程,那么有什么干净的方法可以做到这一点?似乎没有办法从
ScheduledFuture
捕获异常,如果我只是尝试在计划任务上抛出 RuntimeException
,该任务将停止并且永远不会由 ScheduledExecutor
再次运行。
目前,我在主线程中只有一个公共静态成员,用于接收来自计划任务的事件,但这似乎不太理想。有什么推荐的读物供我查看或有什么想法吗?
编辑:抱歉,请允许我用一个例子来扩展这一点:
public class TestScheduledFuture {
public static void main(String[] args) {
ScheduledExecutorService taskScheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> scheduledFuture = taskScheduler.scheduleAtFixedRate(new TestScheduledTask(),2,2, TimeUnit.SECONDS);
}
}
如果我在 TestScheduledTask() 中遇到 RuntimeException,我的目标是简单地在 main() 中抛出 RuntimeException() 。
现在,我在主类中有一个公共静态并发队列,我从计划线程中添加异常。在 main() 中,我只是定期轮询队列并对队列中的任何异常做出反应。有更好的方法吗?
I have a task within a ScheduledExecutor
running on a regular interval. If there are particular exceptions which I want to boil up to the main thread, what is a clean way to do this? There doesn't seem to be a way to catch exceptions from a ScheduledFuture
, and if I simply attempt to throw a RuntimeException
on a scheduled task, that task will cease and never be run again by the ScheduledExecutor
.
Currently, I just have a public static member in the main thread that I use to receive events from scheduled tasks but this hardly seems ideal. Any recommended reading for me to look at or any ideas?
Edit: Apologies, allow me to expand on this with an example:
public class TestScheduledFuture {
public static void main(String[] args) {
ScheduledExecutorService taskScheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> scheduledFuture = taskScheduler.scheduleAtFixedRate(new TestScheduledTask(),2,2, TimeUnit.SECONDS);
}
}
My goal here is to simply throw a RuntimeException() in main() if I ever encounter a RuntimeException within TestScheduledTask().
Right now, I have a public static concurrentQueue in the main class which I add exceptions into from the scheduled threads. Perioidically in main() I simply poll the queue and react to any exceptions in the queue. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
老实说,通过队列将异常传递回另一个线程似乎是一件完全合理的事情。正如见解者所说,另一种方法是使用 Thread.setUncaughtExceptionHandler ,否则异常将不会被 ExecutorService 处理。要使用它,您需要在创建它时提供一个
ThreadFactory
,如下所示Passing the exceptions back to another thread via a queue seems a perfectly reasonable thing to do tbh. An alternative is, as insighter says, use
Thread.setUncaughtExceptionHandler
as otherwise the exception just goes unhandled by theExecutorService
. To use this you need need to supply aThreadFactory
when you create it, something like this