I need to create async thread that runs once with a delay of 2 minutes and that can be killed at any moment. I saw several possible solutions:
ScheduledExecutorServiceandFutureTaskallow me to interrupt a running task, but I will have to invokeshutdown()to terminate all the running threads, and this will block user until the processes were terminated. Also, I will have to frequently invokeThread.interrupted()as described in Enno Shioji’s answer.TimerandTimerTaskdo not require to release running threads, but I have no way to interrupt a running timer thread (Timer.cancel()just cancels future scheduling)- Using Thread and sleep with thread interruption problem.
Is there a good solution? (I’m using tomcat 7)
thank you
After some tests and researches, FutureTask.cancel() and Threads need similar handling of interrupts, as stated in Enno Shioji’s answer
An example that tests interruption flag:
As I understand,
ScheduledExecutorServicemaybe beshutdownwhen application ends running