henix / blog

some notes
0 stars 0 forks source link

exception handling in scheduled tasks #34

Open henix opened 10 years ago

henix commented 10 years ago

http://www.cosmocode.de/en/blog/schoenborn/2009-12/17-uncaught-exceptions-in-scheduled-tasks

如果任务是持续运行的,那么,ScheduledFuture.isDone() 会返回什么?始终是 false?

java.util.concurrent.ScheduledThreadPoolExecutor.ScheduledFutureTask.run():

如果是 periodic ,则调用 FutureTask.runAndReset ,否则调用 run

java.util.concurrent.FutureTask.runAndReset():

不会调用 set ,也就不可能是 NORMAL ,只可能因为抛异常而终止

因此,对于一个 ScheduledFuture:

  1. isDone() 为 true 的情况只有两种: cancel 或 exception
  2. get() 不可能返回,只可能抛异常:CancellationException 或 ExecutionException

如果才能让 scheduled task 在抛异常的情况下继续执行:

http://stackoverflow.com/questions/12346616/how-to-ensure-the-scheduled-executor-runs-even-after-a-runtime-exception

  1. 在 run() 中 catch 所有 Exception
  2. 每隔一段时间 check 一下是否是 isDone()(但这样做本身又需要一个 scheduled task)