How to cancel a task using using cancel(true) in Java?

I have two classes:

class C1 implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        return true;
    }
}

class C2 implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        return true;
    }
}

And I'm using this code:

ExecutorService es = Executors.newFixedThreadPool(1);
Future<Boolean> c1 = es.submit(new C1());
Future<Boolean> c2 = es.submit(new C2());
if (c2.get()) {
    c1.cancel(true);
}
System.out.println(c1.isCancelled());
es.shutdown();

Which produces the expected result:

false

As per my understanding c1.cancel(true); return false, since the task was already completed. What should I do in order to be able to create an operation in which the task can be canceled? Maybe put the thread somehow to sleep? I need this result:

true

Solution 1:

If you want to interrupt your Callable task using Future.cancel(true), then you have to write your task such a way that it is responsive to the interruption. Inside the while loop you can check for the interrupt status, if it is not interrupted you can call Thread.sleep with some timeout. Also note that the Thread.sleep is a blocking interruptible method, which throws an java.lang.InterruptedException when the thread is interrupted while sleeping. Here's how it looks.

class C1 implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        while (!Thread.currentThread().isInterrupted())
            TimeUnit.SECONDS.sleep(1);
        return true;
    }
}

And here's your client program.

final ExecutorService es = Executors.newFixedThreadPool(1);
final Future<Boolean> c1 = es.submit(new C1());
final boolean cancelled = c1.cancel(true);
System.out.println(cancelled);
es.shutdown();