Future task of ExecutorService not truly cancelling

前端 未结 2 1046
南旧
南旧 2020-12-03 01:53

I push my Futures from a ExecutorService into a hash map. Later, I may call cancel on Futures from within the hash map. Although the result is true, I later hit breakpoint

2条回答
  •  再見小時候
    2020-12-03 02:45

    I later hit breakpoints within the Callable procedure, as if the Future cancel() had no effect.

    Future.cancel(true) removes a job that is in the queue and not yet running but if the job is already running it does the equivalent of Thread.interrupt() on the thread running the job. This sets the interrupt bit on the thread and causes any sleep(), wait(), and some other methods to throw InterruptedException.

    It is important to realize that it does not stop the thread. You need to actively check for the interrupt flag in your thread loop or properly handle InterruptedException.

    See my SO answer here for more details: How to suspend thread using thread's id?

提交回复
热议问题