CompletableFuture with delay

Millies, Sebastian Sebastian.Millies at
Sun Aug 24 18:21:08 UTC 2014

Hello there,

I'd like to simulate asynchronous IO events in a test system (without actual IO).
For this purpose, I have defined a method that creates a future which returns a value after a delay.
In contrast to Future#get(Long,TimeUnit) this method does not wait, but uses a separate ScheduledFuture
to complete the future. Code is shown below.

So far, so good. But I also want to cancel the scheduled task (the ScheduledFuture returned from
ScheduledExecutorService#schedule()) when the future is cancelled before the timeout. (So that
I can keep my timeout tasks from piling up when timeouts are long in relation to the real

Please look at the code below, where I create an additional future with whenComplete and use
that to cancel the task. Is that a correct solution? Or could this additional future be optimized
away or be garbage collected? Does the variable "future" that is returned from the method hold a
reference to the additional future? I couldn't tell from the source code of CompletableFuture.

  private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(TIMER_THREADS);

  public static <T> CompletableFuture<T> delayedSuccess(T value, int delay, TimeUnit unit) {
    CompletableFuture<T> future = new CompletableFuture<T>();
    ScheduledFuture<Boolean> task = scheduler.schedule(() -> future.complete(value), delay, unit);
    future.whenComplete((t, ex) -> {
      if (future.isCancelled())
        task.cancel(true);               // <== HERE
    return future;

I fear that this might no longer be the place to ask such questions. If so, could you point
me to an appropriate forum, where I would also be likely to receive an answer?

Sebastian Millies
Expert Java Business Analytics
Phone: +49 681 210 3221 | Fax: +49 681 210 1801 | Sebastian.Millies at<mailto:Sebastian.Millies at>

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 -

More information about the lambda-dev mailing list