Monitoring and restarting the Executor Service and Future Task?
I am working on a multithreading app in Java 5. When it executes it starts several executor services and it has to run for a very long time. I have a monitor service that keeps a check on the state of each created executor. I have read that the executor service may only have the following states:
- running,
- shutting down and
- terminated.
In case anything strange happens during the execution, I have subclassed my own FutureTask class and overriden the methods:
- setException and,
- done (anything unusual like ExecutionException and InterruptedExcept开发者_运维知识库ion are caugth here)
I have a case where an Executor service throws an ExecutionException (in my own FutureTask class). The ExecutionException is caught and logged but my executor service is not logging in anything anymore. My monitor service is outputing the executor service is still alive. Maybe it has to do with the fact that my FutureTask has reached the state done?
- What is the best way to manage this?
- Is it possible to restart the executor service?
- It looks like the FutureTask state affects the Executor service, can I use the FutureTask's state to know the state of the Executor service.
Thanks for your help,
Usually handling exception is best done by the task itself. If your task throws an exception it is finished even if its a scheduled task (it won't run again). In fact if there is any work work you want done after the task has completed its often best done by the same thread in the task also. i.e. only return when there is almost nothing left to do.
EDIT: To prevent a recurring task from dying you can use a try/catch block.
Runnable run = new Runnable() {
public void run() {
try {
// do something which might throw an Exception
} catch(Exception e) {
log.error(e);
}
}
};
scheduledExecutorService.scheduleAtFixedRate(run, delay, period, unit);
If you don't catch the exception and log it, it will be stored in the FutureTask and you have to remember to log it there and restart the task remembering how often to runt he task.
BTW: A task doesn't impact the state of an ExecutorService unless has a reference to it calls it directly. (it won't happen unexpectedly)
BTW2: With the release of Java 7, more than five years after Java 6, its about time to consider migrating from Java 5.0 which has been end of life for over three years.
精彩评论