Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A not-started future that is cancelled still runs. #2750

Open
etsinko opened this issue Aug 22, 2023 · 1 comment
Open

A not-started future that is cancelled still runs. #2750

etsinko opened this issue Aug 22, 2023 · 1 comment

Comments

@etsinko
Copy link

etsinko commented Aug 22, 2023

I found an issue with Future. Basically if future is cancelled before running on an executor it will still run. Here is a snippet that exposes the problem, I'm using a single thread executor:

        ExecutorService es = Executors.newSingleThreadExecutor();

        Future<Void> f = Future
                .run(es, () -> {
                    // We will only see this line
                    System.out.println("Starting Future 1");
                    Thread.sleep(1000);
                    // Will never get here as the future will be cancelled during Thread.sleep()
                    System.out.println("Done Future 1");
                })
                .onComplete(t -> System.out.println("Future 1 result " + t));

        Future<Void> f2 = Future
                .run(es, () -> {
                    // Note, this should never be printed
                    System.out.println("Starting Future 2 ");
                    Thread.sleep(1000);
                    System.out.println("Done Future 2");
                })
                .onComplete(t -> System.out.println("Future 2 result " + t));

        // Cancel f2 BEFORE it runs on the executor
        f2.cancel(true);
        f.cancel(true);
        es.shutdown();

The ouput is as follows:

Starting Future 1
Starting Future 2 
Done Future 2
Future 2 result Failure(java.util.concurrent.CancellationException)
Future 1 result Failure(java.util.concurrent.CancellationException)

I only expected to see Starting Future 1 as f2 is cancelled before executor gets to run it.

@Tchorzyksen37
Copy link

You are right, there is an issue like described above. I did some digging,
f2 has no execution thread assigned, when cancel statement is executed. Future is marked as Cancelled tho.
Now, f is cancelled and thread interrupted. Executor starts execute f2 regardless.
I'm guessing we do not care if result of tryComplete is true or false, and in the end we start it. And can't do nothing about it.

As of today cancel works only for currently running tasks, and one that are completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants