Future.cancel() method is not working

别来无恙 提交于 2019-11-29 07:46:58

Your code does everything right. The only problem is that you're not checking Thread.isInterrupted in the while loop. The only way for thread to get the message is to get to the blocking call Thread.sleep which will immediately throw InterruptedException. If loop is lengthy it can take some time. That's exactly why your code is a little bit unresponsive.

Check for interruption status, say, every 10,000 iterations:

while (i < 100000) {

    if (i % 10000 == 0 && Thread.currentThread().isInterrupted())
        return "fail";

    System.out.println(i++);
}

InterruptedException is for lengthy blocking methods. Thread.isInterrupted is for everything else.

cancel() just calls interrupt() for already executing thread.

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html:

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

Interrupted thread would throw InterruptedException only

when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt() method in class Thread.

So you need to explicitly make job code in executing thread aware of possible interruption.

See also Who is calling the Java Thread interrupt() method if I'm not?.

See also How to cancel Java 8 completable future? as java futures matured only by Java 8.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!