In the code below, the commented out cause the exception that explains us that the timerTask2 is already scheduled or cancelled, however nothing prevents if from being reused and ran by the executor in the code below the commented out part. How it can be explained?

Timer timer2 = new Timer();
TimerTask timerTask2 = new ThreadTest6();
delay = 1000 L;
long period = 1000 L;
timer2.scheduleAtFixedRate(timerTask2, delay, period);

try {
    Thread.sleep(10500);
} catch (InterruptedException e) {
    e.printStackTrace();
}

timer2.purge();
timer2.cancel();
timerTask2.cancel();

//        Timer timer3=new Timer();
//        System.out.println("Task reuse");
//        System.out.println();
//
//        timer3.scheduleAtFixedRate(timerTask2, delay, period);
//
//        try {
//            Thread.sleep(1500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//

System.out.println("At the executor service");
System.out.println();

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
delay = 1000 L;
period = 1000 L;
executor.scheduleAtFixedRate(timerTask2, delay, period, TimeUnit.MILLISECONDS);
try {
    Thread.sleep(delay + period * 3);
} catch (InterruptedException e) {
    e.printStackTrace();
}
executor.shutdown();

0 Answers