The Timer (java.util.Timer) doc describes the cancel method as one that affects the Timer and it states that the timer cannot be used after cancellation. So I instantiate a new Timer. Why will it not let me re-use the argument task0 in this example? I’m not even invoking purge which is described as making tasks GC-eligible. Until it might be explained to be otherwise, I claim Timer class should not affect a TimerTask object that is merely an argument to it.
import java.util.Timer;
import java.util.TimerTask;
public class Tester {
public static void main(String[] args) throws InterruptedException {
long delay = 3000L;
Timer timer0 = new Timer();
Task task0 = new Task();
timer0.schedule(task0, delay);
timer0.cancel();
Timer timer1 = new Timer();
timer1.schedule(task0, delay); // throws an exception if we use task0
Thread.sleep(5000);
timer1.cancel();
}
}
class Task extends TimerTask {
Task() {
}
@Override
public void run() {
System.out.println("task was invoked");
}
}
Allowing this would be error prone, since
task0could still be running when scheduled again by another timer. (Note thatcancel()does not terminate the task.)Note that if
task0is managed by a singleTimer, the same task will never be executed concurrently with itself (regardless if it is executed with fixed-delay or with fixed-rate).If you really want such behavior, the work around would be to let
task0and atask1wrap a common object:And then execute it like this: