[concurrency-interest] CompletableFuture with delay

Zhong Yu zhong.j.yu at gmail.com
Mon Aug 25 14:50:49 EDT 2014


On Mon, Aug 25, 2014 at 11:21 AM, Peter Levart <peter.levart at gmail.com> wrote:
> On 08/25/2014 05:32 PM, Zhong Yu wrote:
>
> If you expose it as CompletableFuture, the caller is able to complete() it.
> If you expose it as CompletionStage, the caller has no way to "cancel()" it.
>
> Also note that CompletableFuture composition does not propagate
> cancellation. If the caller of your supplyAsyncWithTimeout() decides to
> cancel the returned future for some other reason, it will not trigger
> `compute.cancel()` or `task.cancel()`.
>
>     future1 = ...
>     future2 = future1.whenComplete(...)
>     ...
>     future2.cancel()  // does not affect future1
>
>
> I think that's because future2 is dependent on future1 and not vice versa.
> You could have:
>
> future2 = future1.whenComplete(...);
> future3 = future1.whenComplete(...);
>
> Now of course, cancelling future2 should not have an effect on computation
> of future3.
>
> If you call future1.cancel(), then both future2 and future3 will complete
> with CompletionException having the future1's CancelationException as their
> cause...
>
> But that's not what Sebastian is doing. He is returning 'future1' and
> cancelling it does call the completion function.

I was referring to the new code he posted

    supplyAsyncWithTimeout(...) {
        ....
        return compute.applyToEither(...).whenComplete(...)

this is problematic because cancellation on returned future will not
reach inside to cancel `compute` or the scheduled task.

Whether cancellation should propagate by default depends on the target
use cases. In this particular case we see how tedious it is to have to
manually manage cancellation propagation.

Zhong Yu
bayou.io


More information about the Concurrency-interest mailing list