itsmewiththeface
itsmewiththeface

Reputation: 320

Can an Exception thrown by something else cancel an async task?

Let's say I have this Java code that does something asynchronously:

public String main() {
    try {
        // Code before that could throw Exceptions

        CompletableFuture.runAsync(() -> {...});

        // Code after that could throw Exceptions
    } catch (SomeException e) {
        // ...
    } catch (CompletionException e) {
        // ...
    }
}

If this were to run and the Async task successfully starts executing, will it still complete even if something else throws an Exception? If not, how can I let the async call finish executing while the Exception gets thrown?

Upvotes: 1

Views: 527

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

If this were to run and the Async task successfully starts executing, will it still complete even if something else throws an Exception?

yes. The task is not interrupted.

NOTE: If your program exits as a result of an Exception, then the task will be stopped.

If not, how can I let the async call finish executing while the Exception gets thrown?

It does this by default.

If you want to cancel the task however it might ignore the interrupt.

public String main() {
    CompletableFuture future = null;
    try {
        // Code before that could throw Exceptions

        future = CompletableFuture.runAsync(() -> {...});

        // Code after that could throw Exceptions
    } catch (SomeException e) {
        if (future != null) future.cancel(true);
        // ...
    } catch (CompletionException e) {
        // ...
    }
}

Upvotes: 3

Michael
Michael

Reputation: 44100

As long as the task has already started, any exceptions thrown after the call to runAsync will not affect that task.

Exceptions propagate up the call stack. A call stack is local to a particular thread. As your task is running asynchronously (i.e. on another thread), there is no way for an exception thrown on another thread to affect it.

Upvotes: 3

Related Questions