Future cancellation documentation

According to http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html isDone

returns true

if called cancel(boolean mayInterruptIfRunning)

.

After this method returns, subsequent calls to isDone () will always return true.

However, it is possible that the task has started and mayInterruptIfRunning

- false

. So what should be returned isDone()

immediately after this call? true

due to cancellation (what's wrong)?

Also, it is not clear if the method returns cancel(boolean)

false

.

P. S. I am implementing a simple thread pool, so I inherit from Future

.

+3


source to share


1 answer


  • After cancel(...)

    , isDone()

    there should always be true

    . It doesn't matter what you returned cancel(...)

    .
  • If it cancel(...)

    returns true

    , it means that this future is canceled andisCancelled()==true

  • If it cancel(...)

    returns false

    , it means that completion was not caused by this callcancel()

  • cancel(false)

    means that the method cancel

    should not try to cancel a task that is trying to complete the future (meaning "task" depending on the implementation Future

    ), the task will continue to run, but the future is canceled (isDone () == true).
  • cancel(true)

    means there should be an attempt to cancel the running task, whether the attempt is successful or not, the future will be canceled (isDone () == true).

Remember, this is a contract, it must be implemented by the implementation Future

.

Edit: isDone()

always true aftercancel()



Here's an experiment with some of the scenarios:

@Test
public void test() throws ExecutionException, InterruptedException {
    ExecutorService threadExecutor = Executors.newFixedThreadPool(1);
    CompletableFuture c1 = new CompletableFuture();
    CompletableFuture c2 = new CompletableFuture();
    Future<String> future = threadExecutor.submit(() -> {
        try {
            c1.complete(null);
            Thread.sleep(10000);
            c2.complete("normal");
        } catch (InterruptedException e) {
            c2.complete("interrupted");
        }
        return "aaa";
    });
    c1.join(); // waits for the task start
    // future.get(); // awaits the completion
    System.out.println("cancel:     " + future.cancel(true));
    //System.out.println("cancel:     " + future.cancel(false));
    System.out.println("isDone:     " + future.isDone());
    System.out.println("isCanceled: " + future.isCancelled());
    System.out.println("task:       " + c2.join());
}

      

+2


source







All Articles