java - executorService.shutdownNow() doesn't stop the thread -
i have scheduled executor service setup
class test { private final scheduledexecutorservice executor; public test() { executor = executors.newsinglethreadscheduledexecutor((runnable) -> { thread thread = new thread(runnable, this.getclass().getname()); thread.setdaemon(true); return thread; }); executor.schedulewithfixeddelay( new testrefreshtask(), 0, 50000, timeunit.milliseconds ); } private class testrefreshtask implements runnable { @override public void run() { //refresh data refreshdata(); } } public void close() { executor.shutdown(); try { if(!executor.awaittermination(60, timeunit.seconds)) { executor.shutdownnow(); executor.awaittermination(60, timeunit.seconds)); } } catch (interruptedexception e) { //retry dispose task executor.shutdownnow(); thread.currentthread().interrupt(); throw new runtimeexception(e); } } }
to stop thread call close method thread doesn't stop. not sure what's wrong , if somehow supposed handle interruptedexception
in run() code.
- real solution below line. part describes pitfalls.
from javadoc of shutdownnow()
:
there no guarantees beyond best-effort attempts stop processing actively executing tasks. example, typical implementations cancel via thread.interrupt, any task fails respond interrupts may never terminate.
from experience, threads indeed interrupted, according documentation not guaranteed.
however, task not control yourself, it's private task created within schedulewithfixeddelay()
.
from javadoc of schedulewithfixeddelay()
:
if execution of task encounters exception, subsequent executions suppressed. otherwise, task terminate via cancellation or termination of executor.
this means shutdownnow()
not stop thread. cancellation part bit unclear me since runnable
, opposed future
, not have cancel()
method. other reason task stop termination of executor, pool terminates when tasks stop.
the real solution lurks in part javadoc of scheduledthreadpoolexecutor
:
by default, such cancelled task not automatically removed work queue until delay elapses. while enables further inspection , monitoring, may cause unbounded retention of cancelled tasks. avoid this, set setremoveoncancelpolicy true, causes tasks removed work queue @ time of cancellation.
when order executor stop, sets interrupted flag, , if it's scheduledthreadpoolexecutor
, removes task if removeoncancelpolicy
true.
solution:
- execute
executor.setremoveoncancelpolicy(true)
before submitting schedule.
[edit]: since use factory method, not possible implement directly.
make these changes:
private final scheduledthreadpoolexecutor executor;
executor = new scheduledthreadpoolexecutor(1, (runnable) -> {
Comments
Post a Comment