logo
down
shadow

Interrupt CompletableFuture with default value


Interrupt CompletableFuture with default value

By : Denis Ilyichev
Date : November 29 2020, 03:01 PM
wish helps you The future returned by .allOf(resultB, resultC) is only completed when both, resultB and resultC are completed, therefore, the dependent function ignoredVoid -> combine(resultA.join(), resultB.getNow(fallbackB), resultC.getNow(fallbackC) will only get evaluated if resultB and resultC are completed and providing a fallback has no effect at all.
It is generally impossible to react on a get() call within these function. Which should be obvious considering that there can be an arbitrary number of get() calls on the future at different times with different timeouts, but the function passed to thenApply is only evaluated once.
code :
interface FutureFunc<R> {
    R get(long time, TimeUnit u) throws ExecutionException;
}
public FutureFunc<Result> getFuture() {
    CompletableFuture<A> resultA = serviceA.call();
    CompletableFuture<B> resultB = resultA.thenCompose(a -> serviceB.call(a));
    CompletableFuture<C> resultC = resultA.thenCompose(a -> serviceC.call(a));
    CompletableFuture<Result> optimistic = CompletableFuture.allOf(resultB, resultC)
        .thenApply(ignoredVoid -> combine(resultA.join(), resultB.join(), resultC.join()));
    return (t,u) -> {
        try {
            return optimistic.get(t, u);
        } catch (InterruptedException | TimeoutException ex) {
            return combine(resultA.join(), resultB.getNow(fallbackB),
                                           resultC.getNow(fallbackC));
        }
    };
}

public Result extractFuture(FutureFunc<Result> future) {
    Result result;
    try {
        result = future.get(timeOut, MILLISECONDS);
    } catch (ExecutionException ex) {
        ...
    }
    return result;
}
return (t,u) -> {
    try {
        if(resultB.isDone() && resultC.isDone()) return optimistic.get();
        return optimistic.get(t, u);
    } catch (InterruptedException | TimeoutException ex) {
        return combine(resultA.join(), resultB.getNow(fallbackB),
                                       resultC.getNow(fallbackC));
    }
};
public FutureFunc<Result> getFuture() {
    CompletableFuture<A> resultA = serviceA.call();
    CompletableFuture<B> resultB = resultA.thenCompose(a -> serviceB.call(a));
    CompletableFuture<C> resultC = resultA.thenCompose(a -> serviceC.call(a));
    CompletableFuture<Void> bAndC = CompletableFuture.allOf(resultB, resultC);
    CompletableFuture<Result> result = bAndC
        .thenApply(ignoredVoid -> combine(resultA.join(), resultB.join(),
                                                          resultC.join()));
    return (t,u) -> {
        try {
            bAndC.get(t, u);
        } catch (InterruptedException|TimeoutException ex) {
            resultB.complete(fallbackB);
            resultC.complete(fallbackC);
        }
        try {
            return result.get();
        } catch (InterruptedException ex) {
            throw new ExecutionException(ex);
        }
    };
}
public CompletableFuture<Result> getFuture(long timeOut, TimeUnit u) {
    CompletableFuture<A> resultA = serviceA.call();
    CompletableFuture<B> resultB = resultA.thenCompose(a -> serviceB.call(a));
    CompletableFuture<C> resultC = resultA.thenCompose(a -> serviceC.call(a));
    ScheduledExecutorService e = Executors.newSingleThreadScheduledExecutor();
    e.schedule(() -> resultB.complete(fallbackB), timeOut, u);
    e.schedule(() -> resultC.complete(fallbackC), timeOut, u);
    CompletableFuture<Void> bAndC = CompletableFuture.allOf(resultB, resultC);
    bAndC.thenRun(e::shutdown);
    return bAndC.thenApply(ignoredVoid ->
                           combine(resultA.join(), resultB.join(), resultC.join()));
}


Share : facebook icon twitter icon
Java8 CompletableFuture recoverWith equivalent? eg exceptionally but return CompletableFuture<U>

Java8 CompletableFuture recoverWith equivalent? eg exceptionally but return CompletableFuture<U>


By : user3217459
Date : March 29 2020, 07:55 AM
it helps some times After a lot of frustration in trying to figure out the proper way of doing Scala's recoverWith in Java 8, I ended up just writing my own. I still don't know if this is the best approach, but I created something like:
code :
public RecoveryChainAsync<T> recoverWith(Function<Throwable,
                                         CompletableFuture<T>> fn);
How to interrupt underlying execution of CompletableFuture

How to interrupt underlying execution of CompletableFuture


By : Marchetto
Date : March 29 2020, 07:55 AM
Hope that helps A CompletableFuture is not related to the asynchronous action that may eventually complete it.
code :
public static void main(String[] args) throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(1);
    CompletableFuture<String> completable = new CompletableFuture<>();
    Future<?> future = service.submit(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                if (Thread.interrupted()) {
                    return; // remains uncompleted
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    return; // remains uncompleted
                }
            }
            completable.complete("done");
        }
    });

    Thread.sleep(2000);

    // not atomic across the two
    boolean cancelled = future.cancel(true);
    if (cancelled)
        completable.cancel(true); // may not have been cancelled if execution has already completed
    if (completable.isCancelled()) {
        System.out.println("cancelled");
    } else if (completable.isCompletedExceptionally()) {
        System.out.println("exception");
    } else {
        System.out.println("success");
    }
    service.shutdown();
}
How to interrupt CompletableFuture::join?

How to interrupt CompletableFuture::join?


By : Lance Azzato
Date : March 29 2020, 07:55 AM
it fixes the issue Do not use join() if you want to support interruption, use get() instead. Basically they are the same except:
join() is only defined in CompletableFuture whereas get() comes form interface Future join() wraps exceptions in CompletionException whereas get() wraps them in ExecutionException get() might be interrupted and would then throw an InterruptedException
code :
CompletableFuture<Void> myFuture = new CompletableFuture<>();
Thread mainThread = Thread.currentThread();
CompletableFuture.runAsync(() -> {
    try {
        Thread.sleep(1000);
        System.out.println("Interrupting…");
        mainThread.interrupt();
        Thread.sleep(1000);
        System.out.println("Completing");
        myFuture.complete(null);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
try {
    myFuture.get();
    System.out.println("Get succeeded");
} catch (Exception e) {
    System.out.println("Get failed");
    e.printStackTrace();
}
Interrupting…
Get failed
java.lang.InterruptedException
    at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347)
    at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
    at CompletableFutureInteruption.main(CompletableFutureInteruption.java:37)
    …
java CompletableFuture.thenCombine returns CompletableFuture of CompletableFuture

java CompletableFuture.thenCombine returns CompletableFuture of CompletableFuture


By : Petr Govar
Date : March 29 2020, 07:55 AM
it helps some times I have 3 different methods in my application. All are returning CompletableFuture. I want to execute method 1 and 2 in parallel. On completion of method 1 and 2, I want to trigger method 3 with parameters from method 1 and 2 return values. , Suppose you have the Pair class.
code :
class Pair<L, R> {
    public final L left;
    public final R right;

    public Pair(L left, R right) {
        this.left = left;
        this.right = right;
    }
}
CompletableFuture<Request> future1 = RequestConverter.Convert(requestDto);
CompletableFuture<String> future2 = tokenProvider.getAuthToken();

CompletableFuture<String> future3 = future1
    .thenCombine(future2, Pair::new)
    .thenCompose(pair -> requestProcessor.Process(pair.left, pair.right));
Timeout with default value in Java 8 CompletableFuture

Timeout with default value in Java 8 CompletableFuture


By : XXX
Date : March 29 2020, 07:55 AM
hop of those help? CompletableFuture.supplyAsync is just a helper method that creates a CompletableFuture for you, and submits the task to the ForkJoin Pool.
You can create your own supplyAsync with your requirements like this:
shadow
Privacy Policy - Terms - Contact Us © voile276.org