CompletableFuture re-use

2.1k views Asked by At

According to Java 8: Definitive guide to CompletableFuture a CompletableFuture object can only be completed once. When I discovered it I had a simple interface in mind:

public interface Synchronizable<E> {

    CompletableFuture future = new CompletableFuture();

    default E waitFor() throws InterruptedException, ExecutionException {
        return (E) future.get();
    }

    default E waitFor(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return (E) future.get(timeout, unit);
    }

    default void complete(E o) {
        future.complete(o);
    }

    default void complete() {
        complete(null);
    }

}

With the purpose of a thread being able to call waitFor() so that it would wait until another thread calls complete().

Apparently it does not work that way. The first time a cycle like this happens it works fine however the second time; on a totally different class it does not wait and the complete() method of the CompletableFuture class returns false.

So I thought, alright it can only be completed once so why not create a new instance of it to "reset" it? I only use the value once anyways. That doesn't work. In fact it breaks entirely. When I attempt to create a new instance my program goes into a dead-lock!

The article also speaks about a way to pass on values without completing the future (obtrudeValue()). I tried this but it results in the same as the complete() method.

Is there something I can do to prevent this or an alternative that has the functionality I want?

0

There are 0 answers