[concurrency-interest] CompletableFuture with delay

Millies, Sebastian Sebastian.Millies at softwareag.com
Mon Aug 25 11:00:12 EDT 2014

Well, I am supposing that if the future completes normally, that will be due to the task being done. That is, I am supposing that no one else would call complete() on the future. But of course you are correct if I were to go and use the construct in contexts were that assumption might be wrong.

FWIW: here’s how I actually use it to return a default value if an asynchronous supplier times out according to some specified delay. (The reference “future” from the OP is assigned to the reference “useDefault” in the following code, useDefault.cancel() is supposed to trigger the task cancellation and associated cleanup.)


  * Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the

  * value obtained by calling the given Supplier. If the supplier does not return the value before a specified

  * timeout, then the specified default value is used to complete the future. If either future completes, the other

  * will be cancelled.


  public static <T> CompletableFuture<T> supplyAsyncWithTimeout(Supplier<T> supplier, Executor executor, T defaultValue,

    int timeout, TimeUnit unit) {

    CompletableFuture<T> compute = CompletableFuture.supplyAsync(supplier, executor);

    CompletableFuture<T> useDefault = delayedSuccess(defaultValue, timeout, unit);

      return compute.applyToEither(useDefault, Function.identity()).whenComplete((t, ex) -> {





n  Sebastian

From: Zhong Yu [mailto:zhong.j.yu at gmail.com]
Sent: Monday, August 25, 2014 4:43 PM
To: Millies, Sebastian
Cc: concurrency-interest at cs.oswego.edu
Subject: Re: [concurrency-interest] CompletableFuture with delay

On Mon, Aug 25, 2014 at 2:55 AM, Millies, Sebastian <Sebastian.Millies at softwareag.com<mailto:Sebastian.Millies at softwareag.com>> wrote:
    future.whenComplete((t, ex) -> {
      if (future.isCancelled())
        task.cancel(true);               // <== HERE

Shouldn't you always call `task.cancel()`, regardless whether the completion of the future is due to cancellation?
Zhong Yu
P.S. You might want to look into other async APIs in java, like bayou.io<http://bayou.io>

Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140825/ac585153/attachment.html>

More information about the Concurrency-interest mailing list