Can a Java static Timer handle multiple TimerTasks calling cancel()?
So I'm running a Java server and in one class I have a static Timer. Then I have another class which has many instances being created and destroyed throughout the life of the program, each with their own TimerTask (using the static Timer). When an instance is destroyed, it calls cancel() on the TimerTask.
The problem is, I'm not sure if this is good design, and also I get errors sometimes when the instance is creating and scheduling its TimerTask:
java.lang.IllegalStateException: Timer already cancelled.
Here is some code to show what I mean.
/**
* Starts scheduled tasks using TimerTask
*/
private void initTasks()
{
// room heartb开发者_运维技巧eat thread: start immediately, run once every second
roomHeartbeatTask = new RoomHeartbeatTask(this);
RoomListExtension.roomHeartbeat.schedule(roomHeartbeatTask, 0, 1000);
// add additional tasks here
}
/**
* Cancels all tasks that have been started by this extension
*/
private void cancelTasks()
{
roomHeartbeatTask.cancel();
}
The error is because when you call cancel()
the Timer
is 'dead' and you can't do anything else with it.
From the API:
Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
You have a few options:
- Get rid of the static
Timer
and instead hold a separate instance ofTimer
within each object. That way when the object is destroyed, you can also destroy theTimer
without affecting the otherTimerTask
s. This will mean one timer thread per object. - Keep the static
Timer
but also hold in memory (e.g. in anArrayList<TimerTask>
) a list of all the tasks within it. Then when an object is destroyed, you re-create the staticTimer
object using the in-memory list of tasks (minus the one corresponding to the object you destoryed). The consequence of this is that the execution of the remainingTimerTask
s may need some finessing (particularly if you don't want them all to 'bunch up'). - Extend or write your own
Timer
-like class to allow for the removal ofTimerTask
s. (Someone may have already done this, I don't know) - Use a ScheduledThreadPoolExecutor which allows you to remove tasks.
精彩评论