Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Future.cancel(false) returning true for task in execution

Tags:

java

future

Future.cancel(false) should, in my opinion, only return true if it was actually possible to prevent the task's execution.

But from code below we can see that it is contradicting.

As the task is canceld it should not print "Not expecting this statement!!!"

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        final boolean[] canceled = { false };
        ScheduledFuture<?> future = executor.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    if (canceled[0])
                        System.out.println("Not expecting this statement!!!");
                } catch (InterruptedException e) {
                }
            }
        }, 0, TimeUnit.SECONDS);
        Thread.sleep(100);
        canceled[0] = future.cancel(false);

        executor.shutdown();
        executor.awaitTermination(2, TimeUnit.SECONDS);
    }
}

Unfortunately output of this program is "Not expecting this statement!!!"

Can some one explain this behavior.

like image 604
Sachin Sachdeva Avatar asked Oct 21 '25 15:10

Sachin Sachdeva


1 Answers

Because you call canceled[0] = future.cancel(false); with parameter false. From javadoc of Future.cancel:

If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

@param mayInterruptIfRunning {@code true} if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete

When you call cancel, your task has already started and you allow it to complete, so cancel operation is actually successful and return true, if you call canceled[0] = future.cancel(true);, you'll not see the output.

like image 147
shizhz Avatar answered Oct 23 '25 05:10

shizhz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!