How to stop immediately a task which is started using an ExecutorService?

前端 未结 3 1674
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 09:34

I have tried many different ways to immediately stop a task which is started using an ExecutorService, with no luck.

Future future = executorServ         


        
3条回答
  •  广开言路
    2021-01-15 10:01

    Well, the javadoc of Future.cancel(boolean) says that:

    If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

    so it's quite certain that the thread that executes the task is interrupted. What could have happened is that one of the

    ... do many other things here..

    is accidentally clearing the Thread's interrupted status without performing the desired handling. If you'll put a breakpoint in Thread.interrupt() you might catch the criminal.

    Another option I can think of is that the task terminates before capturing the interrupt, either because it's completed or thrown some uncaught exception. Call Future.get() to determine that. Anyway, as asdasd mentioned, it is a good practice to set an UncaughtExceptionHandler.

提交回复
热议问题