Utility of Future.cancel(boolean) method

后端 未结 4 1889
清歌不尽
清歌不尽 2020-12-08 04:24

I was simply exploring the java.util.concurrent package.

I learnt that the class \'Future\' has a method boolean cancel(boolean mayInterrupt

4条回答
  •  情深已故
    2020-12-08 04:50

    The problem that you are overlooking is that only cooperating threads can be stopped safely in Java.

    Indeed, if you look at the Thread API, you will notice that there are some methods called destroy, pause, stop, and resume that were deprecated in Java 1.1. The reason that they were deprecated is that the Java designers realized that they generally can't be used safely. The reasons are explained in the note "Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?".

    The problem is inherent in the Java threading model, and could only be avoided by curtailing the ability of one thread to interact with objects used by other threads. There is a JSR that specifies one one way of doing this ... Isolates ... but no mainstream JVMs implement these APIs to my knowledge.


    So bringing this back to your question, the usefulness of Future.cancel is that it solves the subset of the problem that can be solved in the context of futures.

提交回复
热议问题