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

前端 未结 3 1667
伪装坚强ぢ
伪装坚强ぢ 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 09:56

    I think you'll find solution here. The main point is that cancel method raises InterruptedException. Please check if your thread is still running after cancellation? Are you sure that you didn't try to interrupt finished thread? Are you sure that your thread didn't fail with any other Exception? Try to set up UncaughtExceptionHandler.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-15 10:03

    What you're doing is very dangerous: you're using a thread pool to execute tasks (which I'll call downloaders), and the same thread pool to execute tasks which

    • wait for the downloaders to finish (which I'll call controllers)
    • or ask the controllers to stop

    This means that if the core number of threads is reached after the controller has started, the downloaders will be put in the queue of the thread pool, and the controller thread will never finish. Similarly, if the core number of threads is reached when you execute the cancelling task, this cancelling task will be put in the queue, and won't execute until some other task is finished.

    You should probably use a thread pool for downloaders, another one for controllers, and the current thread to cancel the controllers.

    0 讨论(0)
提交回复
热议问题