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 heartbeat 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()theTimeris ‘dead’ and you can’t do anything else with it.From the API:
You have a few options:
Timerand instead hold a separate instance ofTimerwithin each object. That way when the object is destroyed, you can also destroy theTimerwithout affecting the otherTimerTasks. This will mean one timer thread per object.Timerbut 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 staticTimerobject 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 remainingTimerTasks may need some finessing (particularly if you don’t want them all to ‘bunch up’).Timer-like class to allow for the removal ofTimerTasks. (Someone may have already done this, I don’t know)