completablefuture: CompletableFuture module (thenApply vs thenCompose and the serial trap, which thread runs a stage incl. join() running dependents, CompletionException wrapping, orTimeout/cancel not stopping work, allOf/anyOf with fail-fast and first-success helpers, virtual-thread timings, StructuredTaskScope preview error), 26 contract tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3dRuKRhrHFPzWSSxr
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
59a5435825
commit
9c2ae10d7f
@@ -0,0 +1,15 @@
|
||||
import java.util.concurrent.StructuredTaskScope;
|
||||
|
||||
/**
|
||||
* Deliberately NOT part of the build (it lives outside src/main). scripts/compile-broken.sh runs
|
||||
* javac on it so the compiler's own message can be committed to output/.
|
||||
*
|
||||
* StructuredTaskScope is a preview API in JDK 25, so this fails without --enable-preview.
|
||||
*/
|
||||
public class StructuredScopeWithoutPreview {
|
||||
public static void main(String[] args) throws Exception {
|
||||
try (var scope = StructuredTaskScope.open()) {
|
||||
scope.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.describe;
|
||||
import static com.ankurm.completablefuture.Util.sleep;
|
||||
|
||||
/** allOf and anyOf: what they return, when they complete, and the two helpers you end up writing. */
|
||||
public class AllOfAnyOfDemo {
|
||||
|
||||
static CompletableFuture<String> after(long ms, String value, ExecutorService pool) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
sleep(ms);
|
||||
return value;
|
||||
}, pool);
|
||||
}
|
||||
|
||||
static CompletableFuture<String> failAfter(long ms, ExecutorService pool) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
sleep(ms);
|
||||
throw new IllegalStateException("failed after " + ms + " ms");
|
||||
}, pool);
|
||||
}
|
||||
|
||||
/** Completes as soon as ANY input fails; completes normally only when ALL succeed. */
|
||||
static CompletableFuture<Void> allOrFailFast(List<? extends CompletableFuture<?>> futures) {
|
||||
CompletableFuture<Void> result = new CompletableFuture<>();
|
||||
futures.forEach(f -> f.whenComplete((v, ex) -> {
|
||||
if (ex != null) {
|
||||
result.completeExceptionally(ex);
|
||||
}
|
||||
}));
|
||||
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).thenRun(() -> result.complete(null));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Completes with the first SUCCESS; fails only if every input fails. */
|
||||
static <T> CompletableFuture<T> firstSuccess(List<CompletableFuture<T>> futures) {
|
||||
CompletableFuture<T> result = new CompletableFuture<>();
|
||||
AtomicInteger failures = new AtomicInteger();
|
||||
for (CompletableFuture<T> f : futures) {
|
||||
f.whenComplete((v, ex) -> {
|
||||
if (ex == null) {
|
||||
result.complete(v);
|
||||
} else if (failures.incrementAndGet() == futures.size()) {
|
||||
result.completeExceptionally(ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
|
||||
|
||||
System.out.println("== 1. allOf returns CompletableFuture<Void> - you collect results yourself");
|
||||
CompletableFuture<String> a = after(50, "a", pool);
|
||||
CompletableFuture<String> b = after(80, "b", pool);
|
||||
CompletableFuture<String> c = after(30, "c", pool);
|
||||
CompletableFuture<List<String>> all = CompletableFuture.allOf(a, b, c)
|
||||
.thenApply(v -> List.of(a.join(), b.join(), c.join()));
|
||||
System.out.println("collected: " + all.join());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. allOf with one early failure: it waits for the slow one anyway");
|
||||
AtomicBoolean slowDone = new AtomicBoolean();
|
||||
CompletableFuture<String> early = failAfter(50, pool);
|
||||
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(400);
|
||||
slowDone.set(true);
|
||||
return "slow ok";
|
||||
}, pool);
|
||||
long t0 = System.nanoTime();
|
||||
try {
|
||||
CompletableFuture.allOf(early, slow).join();
|
||||
} catch (CompletionException e) {
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
System.out.println("allOf failed with: " + describe(e));
|
||||
System.out.println("after " + ms + " ms (the failure itself happened at 50 ms)");
|
||||
System.out.println("slow task finished by then? " + slowDone.get());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. allOrFailFast: fail at the first failure, but nothing is cancelled");
|
||||
AtomicBoolean slow2Done = new AtomicBoolean();
|
||||
CompletableFuture<String> early2 = failAfter(50, pool);
|
||||
CompletableFuture<String> slow2 = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(400);
|
||||
slow2Done.set(true);
|
||||
return "slow ok";
|
||||
}, pool);
|
||||
long t1 = System.nanoTime();
|
||||
try {
|
||||
allOrFailFast(List.of(early2, slow2)).join();
|
||||
} catch (CompletionException e) {
|
||||
long ms = (System.nanoTime() - t1) / 1_000_000;
|
||||
System.out.println("failed with: " + describe(e));
|
||||
System.out.println("after " + ms + " ms");
|
||||
System.out.println("slow task finished by then? " + slow2Done.get());
|
||||
}
|
||||
sleep(450);
|
||||
System.out.println("slow task finished 450 ms later? " + slow2Done.get());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. anyOf returns the first COMPLETION, and a failure counts");
|
||||
CompletableFuture<Object> any = CompletableFuture.anyOf(failAfter(30, pool), after(100, "slow ok", pool));
|
||||
try {
|
||||
System.out.println("anyOf result: " + any.join());
|
||||
} catch (CompletionException e) {
|
||||
System.out.println("anyOf failed with: " + describe(e));
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. firstSuccess: skip failures, take the first value");
|
||||
String winner = firstSuccess(List.of(failAfter(30, pool), after(100, "slow ok", pool), after(300, "slower", pool))).join();
|
||||
System.out.println("firstSuccess result: " + winner);
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.describe;
|
||||
|
||||
/**
|
||||
* What exceptionally, handle and whenComplete actually receive - and what join() and get() throw.
|
||||
*
|
||||
* <p>The surprise is the wrapper: depending on how a future failed and where in the chain you
|
||||
* are looking, you see either the raw exception or a CompletionException around it.
|
||||
*/
|
||||
public class ExceptionHandlingDemo {
|
||||
|
||||
static CompletableFuture<Integer> failing() {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
throw new IllegalStateException("boom");
|
||||
});
|
||||
}
|
||||
|
||||
static CompletableFuture<Integer> failedDirectly() {
|
||||
CompletableFuture<Integer> f = new CompletableFuture<>();
|
||||
f.completeExceptionally(new IllegalStateException("boom"));
|
||||
return f;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
System.out.println("== 1. What does exceptionally() receive?");
|
||||
failing().exceptionally(ex -> {
|
||||
System.out.println("supplyAsync threw, exceptionally on same stage: " + describe(ex));
|
||||
return -1;
|
||||
}).join();
|
||||
|
||||
failedDirectly().exceptionally(ex -> {
|
||||
System.out.println("completeExceptionally(raw), same stage: " + describe(ex));
|
||||
return -1;
|
||||
}).join();
|
||||
|
||||
failedDirectly().thenApply(x -> x + 1).exceptionally(ex -> {
|
||||
System.out.println("completeExceptionally(raw), one stage later: " + describe(ex));
|
||||
return -1;
|
||||
}).join();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. What do join() and get() throw?");
|
||||
try {
|
||||
failing().join();
|
||||
} catch (CompletionException e) {
|
||||
System.out.println("join(): " + describe(e));
|
||||
}
|
||||
try {
|
||||
failing().get();
|
||||
} catch (ExecutionException e) {
|
||||
System.out.println("get(): " + describe(e));
|
||||
}
|
||||
CompletableFuture<Integer> f = failing();
|
||||
try {
|
||||
f.join();
|
||||
} catch (CompletionException ignored) {
|
||||
// state() and exceptionNow() are the non-throwing way to look (JDK 19+)
|
||||
}
|
||||
System.out.println("state() = " + f.state() + ", exceptionNow() = " + describe(f.exceptionNow()));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. exceptionally vs handle vs whenComplete");
|
||||
int viaExceptionally = failing().exceptionally(ex -> -1).join();
|
||||
int viaHandle = failing().handle((v, ex) -> ex == null ? v : -2).join();
|
||||
System.out.println("exceptionally(ex -> -1) -> " + viaExceptionally);
|
||||
System.out.println("handle((v, ex) -> ex==null?v:-2) -> " + viaHandle);
|
||||
|
||||
CompletableFuture<Integer> observed = failing().whenComplete((v, ex) ->
|
||||
System.out.println("whenComplete saw: " + describe(ex)));
|
||||
try {
|
||||
observed.join();
|
||||
} catch (CompletionException e) {
|
||||
System.out.println("whenComplete did not recover; join(): " + describe(e));
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. On success, each one is a pass-through or a transformer");
|
||||
System.out.println("exceptionally on success: " + CompletableFuture.completedFuture(7).exceptionally(ex -> -1).join());
|
||||
System.out.println("handle on success: " + CompletableFuture.completedFuture(7).handle((v, ex) -> ex == null ? v * 2 : -2).join());
|
||||
System.out.println("whenComplete on success: " + CompletableFuture.completedFuture(7).whenComplete((v, ex) -> { }).join());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. exceptionallyCompose: recover with another async call (JDK 12+)");
|
||||
int recovered = failing()
|
||||
.exceptionallyCompose(ex -> CompletableFuture.supplyAsync(() -> 99))
|
||||
.join();
|
||||
System.out.println("recovered value: " + recovered);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.await;
|
||||
|
||||
/**
|
||||
* A thread blocked in join() can run the dependent stages of the future it is waiting on.
|
||||
*
|
||||
* <p>Same code, same guarantee that the dependent stage was registered before the source
|
||||
* finished. The only difference between the two loops is how main waits for the source. The counts are
|
||||
* measured, not asserted: the first loop varies from run to run, the second does not.
|
||||
*/
|
||||
public class JoinHelpsDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int trials = Integer.getInteger("trials", 200);
|
||||
|
||||
Thread main = Thread.currentThread();
|
||||
AtomicReference<StackTraceElement[]> sample = new AtomicReference<>();
|
||||
|
||||
int ranOnMainWhenJoining = 0;
|
||||
for (int i = 0; i < trials; i++) {
|
||||
CountDownLatch gate = new CountDownLatch(1);
|
||||
AtomicReference<Thread> ranOn = new AtomicReference<>();
|
||||
CompletableFuture<String> source = CompletableFuture.supplyAsync(() -> {
|
||||
await(gate);
|
||||
return "x";
|
||||
});
|
||||
CompletableFuture<Void> stage = source.thenAccept(v -> {
|
||||
ranOn.set(Thread.currentThread());
|
||||
if (Thread.currentThread() == main) {
|
||||
sample.compareAndSet(null, new Throwable().getStackTrace()); // keep the first one
|
||||
}
|
||||
});
|
||||
gate.countDown();
|
||||
source.join(); // main waits by calling join() on the source: this is where it may run the stage
|
||||
stage.join(); // then make sure the stage has finished, whichever thread ran it
|
||||
if (ranOn.get() == Thread.currentThread()) {
|
||||
ranOnMainWhenJoining++;
|
||||
}
|
||||
}
|
||||
|
||||
int ranOnMainWhenLatching = 0;
|
||||
for (int i = 0; i < trials; i++) {
|
||||
CountDownLatch gate = new CountDownLatch(1);
|
||||
CountDownLatch done = new CountDownLatch(1);
|
||||
AtomicReference<Thread> ranOn = new AtomicReference<>();
|
||||
CompletableFuture<String> source = CompletableFuture.supplyAsync(() -> {
|
||||
await(gate);
|
||||
return "x";
|
||||
});
|
||||
source.thenAccept(v -> {
|
||||
ranOn.set(Thread.currentThread());
|
||||
done.countDown();
|
||||
});
|
||||
gate.countDown();
|
||||
await(done); // main waits on a latch, never calls into the future
|
||||
if (ranOn.get() == Thread.currentThread()) {
|
||||
ranOnMainWhenLatching++;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("trials per loop: " + trials);
|
||||
System.out.println("stage ran on main when main waited with join(): " + ranOnMainWhenJoining);
|
||||
System.out.println("stage ran on main when main waited on a CountDownLatch: " + ranOnMainWhenLatching);
|
||||
|
||||
StackTraceElement[] frames = sample.get();
|
||||
if (frames != null) {
|
||||
System.out.println();
|
||||
System.out.println("stack of the first stage that ran on main while it was inside join():");
|
||||
for (StackTraceElement f : frames) {
|
||||
System.out.println(" at " + f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.sleep;
|
||||
import static com.ankurm.completablefuture.Util.timed;
|
||||
|
||||
/**
|
||||
* thenApply vs thenCompose vs thenCombine.
|
||||
*
|
||||
* <p>The rule: if your function returns a plain value, use thenApply. If it returns another
|
||||
* CompletableFuture, use thenCompose. If the two calls do not depend on each other, start both
|
||||
* first and join them with thenCombine. The last case is the one people get wrong, because
|
||||
* thenCompose compiles and returns the right answer - it is just serial.
|
||||
*/
|
||||
public class ThenApplyVsComposeDemo {
|
||||
|
||||
record User(long id, String name) {}
|
||||
|
||||
record Order(long userId, String item) {}
|
||||
|
||||
static CompletableFuture<User> fetchUser(long id, ExecutorService io) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
sleep(100);
|
||||
return new User(id, "ankur");
|
||||
}, io);
|
||||
}
|
||||
|
||||
static CompletableFuture<Order> fetchLastOrder(User user, ExecutorService io) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
sleep(150);
|
||||
return new Order(user.id(), "laptop");
|
||||
}, io);
|
||||
}
|
||||
|
||||
static CompletableFuture<String> fetchBanner(ExecutorService io) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
sleep(120);
|
||||
return "winter-sale";
|
||||
}, io);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (ExecutorService io = Executors.newFixedThreadPool(4)) {
|
||||
|
||||
System.out.println("== 1. thenApply with a function that itself returns a CompletableFuture");
|
||||
CompletableFuture<CompletableFuture<Order>> nested =
|
||||
fetchUser(1, io).thenApply(user -> fetchLastOrder(user, io));
|
||||
Object inner = nested.join();
|
||||
System.out.println("nested.join() is a: " + inner.getClass().getSimpleName());
|
||||
System.out.println("inner.join() is: " + ((CompletableFuture<?>) inner).join());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. thenCompose flattens it");
|
||||
CompletableFuture<Order> flat =
|
||||
fetchUser(1, io).thenCompose(user -> fetchLastOrder(user, io));
|
||||
System.out.println("flat.join() is: " + flat.join());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. Same three tools, measured (fixed pool of 4, so nothing queues)");
|
||||
timed("dependent calls: thenCompose (100 ms then 150 ms)",
|
||||
() -> fetchUser(1, io).thenCompose(user -> fetchLastOrder(user, io)));
|
||||
|
||||
timed("independent calls: start both, then thenCombine",
|
||||
() -> {
|
||||
CompletableFuture<User> user = fetchUser(1, io);
|
||||
CompletableFuture<String> banner = fetchBanner(io);
|
||||
return user.thenCombine(banner, (u, b) -> u.name() + " + " + b);
|
||||
});
|
||||
|
||||
timed("independent calls, wrongly chained with thenCompose",
|
||||
() -> fetchUser(1, io)
|
||||
.thenCompose(user -> fetchBanner(io).thenApply(b -> user.name() + " + " + b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.describe;
|
||||
import static com.ankurm.completablefuture.Util.sleep;
|
||||
|
||||
/**
|
||||
* orTimeout and completeOnTimeout (JDK 9+) complete the FUTURE. They do not stop the WORK.
|
||||
* cancel(true) behaves the same way, despite its argument being called mayInterruptIfRunning.
|
||||
*/
|
||||
public class TimeoutDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
|
||||
|
||||
System.out.println("== 1. orTimeout: the future fails, the task keeps running");
|
||||
AtomicBoolean finished = new AtomicBoolean();
|
||||
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(600);
|
||||
finished.set(true);
|
||||
return "late result";
|
||||
}, pool).orTimeout(100, TimeUnit.MILLISECONDS);
|
||||
try {
|
||||
slow.join();
|
||||
} catch (CompletionException e) {
|
||||
System.out.println("join() after 100 ms: " + describe(e));
|
||||
}
|
||||
System.out.println("task finished right after that? " + finished.get());
|
||||
sleep(700);
|
||||
System.out.println("task finished 700 ms later? " + finished.get());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. completeOnTimeout: a fallback value instead of an exception");
|
||||
String value = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(600);
|
||||
return "real value";
|
||||
}, pool).completeOnTimeout("fallback value", 100, TimeUnit.MILLISECONDS).join();
|
||||
System.out.println("join() returned: " + value);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. cancel(true) does not interrupt the task either");
|
||||
AtomicBoolean sawInterrupt = new AtomicBoolean();
|
||||
AtomicBoolean ranToEnd = new AtomicBoolean();
|
||||
CompletableFuture<String> cancelled = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
Thread.sleep(400);
|
||||
} catch (InterruptedException e) {
|
||||
sawInterrupt.set(true);
|
||||
}
|
||||
ranToEnd.set(true);
|
||||
return "x";
|
||||
}, pool);
|
||||
sleep(50);
|
||||
System.out.println("cancel(true) returned: " + cancelled.cancel(true));
|
||||
try {
|
||||
cancelled.join();
|
||||
} catch (CancellationException e) {
|
||||
System.out.println("join(): " + e.getClass().getSimpleName());
|
||||
}
|
||||
sleep(500);
|
||||
System.out.println("task saw an interrupt? " + sawInterrupt.get());
|
||||
System.out.println("task ran to the end anyway? " + ranToEnd.get());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. The fix: keep the executor's Future and cancel THAT on timeout");
|
||||
AtomicBoolean interrupted = new AtomicBoolean();
|
||||
CompletableFuture<String> result = new CompletableFuture<>();
|
||||
Future<?> handle = pool.submit(() -> {
|
||||
try {
|
||||
Thread.sleep(400);
|
||||
result.complete("done");
|
||||
} catch (InterruptedException e) {
|
||||
interrupted.set(true);
|
||||
}
|
||||
});
|
||||
result.orTimeout(100, TimeUnit.MILLISECONDS).whenComplete((v, ex) -> {
|
||||
if (ex instanceof TimeoutException) {
|
||||
handle.cancel(true);
|
||||
}
|
||||
});
|
||||
try {
|
||||
result.join();
|
||||
} catch (CompletionException e) {
|
||||
System.out.println("join(): " + describe(e));
|
||||
}
|
||||
sleep(100);
|
||||
System.out.println("task saw an interrupt? " + interrupted.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Tiny helpers shared by the demos. Nothing here is CompletableFuture-specific. */
|
||||
final class Util {
|
||||
|
||||
private Util() {}
|
||||
|
||||
/** Sleeps, and turns an interrupt into an unchecked exception so lambdas stay readable. */
|
||||
static void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("interrupted while sleeping", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits on a latch, turning an interrupt into an unchecked exception. */
|
||||
static void await(java.util.concurrent.CountDownLatch latch) {
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("interrupted while waiting", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Thread name, with virtual threads (which have an empty name) labelled explicitly. */
|
||||
static String threadName() {
|
||||
Thread t = Thread.currentThread();
|
||||
return t.isVirtual() ? "virtual-thread" : t.getName();
|
||||
}
|
||||
|
||||
/** Runs the supplier, joins the future it returns, and prints the result with wall-clock time. */
|
||||
static <T> T timed(String label, Supplier<CompletableFuture<T>> work) {
|
||||
long t0 = System.nanoTime();
|
||||
T result = work.get().join();
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
System.out.printf("%-58s -> %-34s %5d ms%n", label, result, ms);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** One-line description of a throwable: its class, message, and cause chain head. */
|
||||
static String describe(Throwable ex) {
|
||||
if (ex == null) {
|
||||
return "null";
|
||||
}
|
||||
String s = ex.getClass().getSimpleName();
|
||||
if (ex.getCause() != null) {
|
||||
s += " <- cause " + ex.getCause().getClass().getSimpleName() + ": " + ex.getCause().getMessage();
|
||||
} else if (ex.getMessage() != null) {
|
||||
s += ": " + ex.getMessage();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.sleep;
|
||||
|
||||
/**
|
||||
* Where do virtual threads win? Blocking work, by a lot. CPU-bound work, not at all.
|
||||
*
|
||||
* <p>Wall-clock numbers, one run each after a warm-up. Indicative, not a JMH result: the figures
|
||||
* to trust are the ratios, and the figures to distrust are the absolute milliseconds.
|
||||
*/
|
||||
public class VirtualThreadsBenchmark {
|
||||
|
||||
static final int BLOCKING_TASKS = Integer.getInteger("blockingTasks", 300);
|
||||
static final int BLOCKING_MS = Integer.getInteger("blockingMs", 50);
|
||||
static final int CPU_TASKS = Integer.getInteger("cpuTasks", 16);
|
||||
static final int CPU_ROUNDS = Integer.getInteger("cpuRounds", 2_000_000);
|
||||
|
||||
/** Starts every task via supplyAsync, waits for all, returns elapsed milliseconds. */
|
||||
static long run(int tasks, Supplier<Integer> body, Executor executor) {
|
||||
long t0 = System.nanoTime();
|
||||
List<CompletableFuture<Integer>> futures = IntStream.range(0, tasks)
|
||||
.mapToObj(i -> executor == null
|
||||
? CompletableFuture.supplyAsync(body)
|
||||
: CompletableFuture.supplyAsync(body, executor))
|
||||
.toList();
|
||||
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
|
||||
return (System.nanoTime() - t0) / 1_000_000;
|
||||
}
|
||||
|
||||
static int blocking() {
|
||||
sleep(BLOCKING_MS);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int cpu() {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] data = new byte[32];
|
||||
for (int i = 0; i < CPU_ROUNDS; i++) {
|
||||
data = md.digest(data);
|
||||
}
|
||||
return data[0];
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void row(String label, long ms) {
|
||||
System.out.printf(" %-46s %7d ms%n", label, ms);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
System.out.println("availableProcessors = " + cores);
|
||||
System.out.println("common pool parallelism = " + ForkJoinPool.getCommonPoolParallelism());
|
||||
|
||||
// Warm-up so class loading and JIT do not land in the first row.
|
||||
try (ExecutorService warm = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
run(50, VirtualThreadsBenchmark::blocking, warm);
|
||||
run(2, VirtualThreadsBenchmark::cpu, warm);
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.printf("== Blocking work: %d tasks, each sleeping %d ms (a stand-in for a remote call)%n",
|
||||
BLOCKING_TASKS, BLOCKING_MS);
|
||||
row("default async pool (no executor argument)", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, null));
|
||||
try (ExecutorService fixed50 = Executors.newFixedThreadPool(50)) {
|
||||
row("fixed pool, 50 threads", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, fixed50));
|
||||
}
|
||||
try (ExecutorService fixed200 = Executors.newFixedThreadPool(200)) {
|
||||
row("fixed pool, 200 threads", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, fixed200));
|
||||
}
|
||||
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
row("virtual thread per task", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, virtual));
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.printf("== CPU-bound work: %d tasks, each %,d rounds of SHA-256%n", CPU_TASKS, CPU_ROUNDS);
|
||||
long t0 = System.nanoTime();
|
||||
IntStream.range(0, CPU_TASKS).forEach(i -> cpu());
|
||||
row("sequential, one thread (baseline)", (System.nanoTime() - t0) / 1_000_000);
|
||||
row("default async pool (no executor argument)", run(CPU_TASKS, VirtualThreadsBenchmark::cpu, null));
|
||||
try (ExecutorService fixed = Executors.newFixedThreadPool(cores)) {
|
||||
row("fixed pool, " + cores + " threads (= cores)", run(CPU_TASKS, VirtualThreadsBenchmark::cpu, fixed));
|
||||
}
|
||||
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
row("virtual thread per task", run(CPU_TASKS, VirtualThreadsBenchmark::cpu, virtual));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.await;
|
||||
import static com.ankurm.completablefuture.Util.threadName;
|
||||
|
||||
/**
|
||||
* Which thread runs each stage?
|
||||
*
|
||||
* <p>The answer depends on two things: whether the stage was registered before or after the
|
||||
* previous stage finished, and whether you used the Async variant (and which executor).
|
||||
*
|
||||
* <p>Two details keep the transcript stable. A latch holds the first stage open until every
|
||||
* dependent stage is registered, so "registered before it finished" is guaranteed. And main waits
|
||||
* on a second latch instead of calling join(): a thread blocked in join() can run dependent stages
|
||||
* itself (see JoinHelpsDemo), which would make this output vary between runs.
|
||||
*/
|
||||
public class WhichThreadDemo {
|
||||
|
||||
private static final Map<String, String> lines = new ConcurrentHashMap<>();
|
||||
|
||||
/** Records which thread this stage ran on, then counts the latch down. */
|
||||
static void record(String key, String label, CountDownLatch done) {
|
||||
lines.put(key, String.format("%-52s ran on %s", label, threadName()));
|
||||
done.countDown();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("availableProcessors = " + Runtime.getRuntime().availableProcessors());
|
||||
System.out.println("common pool parallelism = " + ForkJoinPool.getCommonPoolParallelism());
|
||||
System.out.println("caller thread = " + threadName());
|
||||
System.out.println();
|
||||
|
||||
AtomicInteger n = new AtomicInteger();
|
||||
try (ExecutorService mine = Executors.newFixedThreadPool(2, r -> new Thread(r, "my-pool-" + n.incrementAndGet()))) {
|
||||
|
||||
System.out.println("== Stage registered WHILE the previous stage is still running");
|
||||
CountDownLatch gate = new CountDownLatch(1);
|
||||
CountDownLatch done = new CountDownLatch(4);
|
||||
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
|
||||
await(gate);
|
||||
record("1", "supplyAsync body", done);
|
||||
return "x";
|
||||
});
|
||||
slow.thenApply(v -> { record("2", "thenApply (registered before slow finished)", done); return v; });
|
||||
slow.thenApplyAsync(v -> { record("3", "thenApplyAsync (no executor)", done); return v; });
|
||||
slow.thenApplyAsync(v -> { record("4", "thenApplyAsync (executor = mine)", done); return v; }, mine);
|
||||
gate.countDown(); // every stage is registered; now let slow finish
|
||||
await(done);
|
||||
for (String k : new String[] {"1", "2", "3", "4"}) {
|
||||
System.out.println(lines.get(k));
|
||||
}
|
||||
while (!slow.isDone()) {
|
||||
Thread.yield(); // isDone() does not run any stage, unlike join()
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== Stage registered AFTER the previous stage finished");
|
||||
CountDownLatch after = new CountDownLatch(2);
|
||||
slow.thenApply(v -> { record("5", "thenApply (registered after slow finished)", after); return v; });
|
||||
CompletableFuture.completedFuture("x")
|
||||
.thenApply(v -> { record("6", "thenApply on completedFuture(..)", after); return v; });
|
||||
await(after);
|
||||
System.out.println(lines.get("5"));
|
||||
System.out.println(lines.get("6"));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== Supplying with your own executor");
|
||||
CountDownLatch gate2 = new CountDownLatch(1);
|
||||
CountDownLatch done2 = new CountDownLatch(2);
|
||||
CompletableFuture<String> body = CompletableFuture.supplyAsync(() -> {
|
||||
await(gate2);
|
||||
record("7", "supplyAsync(.., mine) body", done2);
|
||||
return "x";
|
||||
}, mine);
|
||||
body.thenApply(v -> { record("8", "thenApply after supplyAsync(.., mine)", done2); return v; });
|
||||
gate2.countDown();
|
||||
await(done2);
|
||||
System.out.println(lines.get("7"));
|
||||
System.out.println(lines.get("8"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
package com.ankurm.completablefuture;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static com.ankurm.completablefuture.Util.sleep;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Pins the behaviours the article states. Timing assertions use generous bounds: they check the
|
||||
* SHAPE (waited for the slow one, failed fast) and not an exact millisecond figure.
|
||||
*/
|
||||
class CompletableFutureContractTest {
|
||||
|
||||
// ---- thenApply / thenCompose ------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void thenApplyWithAFutureReturningFunctionGivesANestedFuture() {
|
||||
CompletableFuture<CompletableFuture<Integer>> nested =
|
||||
CompletableFuture.completedFuture(1).thenApply(x -> CompletableFuture.completedFuture(x + 1));
|
||||
assertInstanceOf(CompletableFuture.class, nested.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thenComposeFlattensIt() {
|
||||
CompletableFuture<Integer> flat =
|
||||
CompletableFuture.completedFuture(1).thenCompose(x -> CompletableFuture.completedFuture(x + 1));
|
||||
assertEquals(2, flat.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void independentCallsChainedWithThenComposeAreSerial() throws Exception {
|
||||
try (ExecutorService io = Executors.newFixedThreadPool(4)) {
|
||||
long t0 = System.nanoTime();
|
||||
CompletableFuture.supplyAsync(() -> { sleep(150); return 1; }, io)
|
||||
.thenCompose(a -> CompletableFuture.supplyAsync(() -> { sleep(150); return a + 1; }, io))
|
||||
.join();
|
||||
long chainedMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
|
||||
long t1 = System.nanoTime();
|
||||
CompletableFuture<Integer> x = CompletableFuture.supplyAsync(() -> { sleep(150); return 1; }, io);
|
||||
CompletableFuture<Integer> y = CompletableFuture.supplyAsync(() -> { sleep(150); return 1; }, io);
|
||||
x.thenCombine(y, Integer::sum).join();
|
||||
long combinedMs = (System.nanoTime() - t1) / 1_000_000;
|
||||
|
||||
assertTrue(chainedMs >= 290, "chained should be about the sum, was " + chainedMs);
|
||||
assertTrue(combinedMs < 280, "combined should be about the max, was " + combinedMs);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- which thread -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void stageRegisteredAfterCompletionRunsOnTheCallingThread() {
|
||||
AtomicReference<Thread> ranOn = new AtomicReference<>();
|
||||
CompletableFuture.completedFuture("x").thenApply(v -> { ranOn.set(Thread.currentThread()); return v; }).join();
|
||||
assertSame(Thread.currentThread(), ranOn.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageRegisteredBeforeCompletionRunsOnTheCompletingThread() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(1, r -> new Thread(r, "completer"))) {
|
||||
AtomicReference<String> ranOn = new AtomicReference<>();
|
||||
CountDownLatch gate = new CountDownLatch(1);
|
||||
CountDownLatch done = new CountDownLatch(1);
|
||||
CompletableFuture.supplyAsync(() -> { Util.await(gate); return "x"; }, pool)
|
||||
.thenApply(v -> { ranOn.set(Thread.currentThread().getName()); done.countDown(); return v; });
|
||||
gate.countDown(); // the dependent stage is registered; now let the first one finish
|
||||
Util.await(done); // wait on a latch: calling join() here could run the stage on this thread
|
||||
assertEquals("completer", ranOn.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mainNeverRunsARegisteredStageWhenItWaitsOnALatch() {
|
||||
for (int i = 0; i < 50; i++) {
|
||||
CountDownLatch gate = new CountDownLatch(1);
|
||||
CountDownLatch done = new CountDownLatch(1);
|
||||
AtomicReference<Thread> ranOn = new AtomicReference<>();
|
||||
CompletableFuture.supplyAsync(() -> { Util.await(gate); return "x"; })
|
||||
.thenAccept(v -> { ranOn.set(Thread.currentThread()); done.countDown(); });
|
||||
gate.countDown();
|
||||
Util.await(done);
|
||||
assertNotSame(Thread.currentThread(), ranOn.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void thenApplyAsyncWithExecutorRunsOnThatExecutor() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(1, r -> new Thread(r, "mine"))) {
|
||||
String name = CompletableFuture.completedFuture("x")
|
||||
.thenApplyAsync(v -> Thread.currentThread().getName(), pool).join();
|
||||
assertEquals("mine", name);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- exceptions -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void exceptionallyOnAFailedSupplyAsyncSeesTheCompletionExceptionWrapper() {
|
||||
Throwable seen = CompletableFuture.<Integer>supplyAsync(() -> { throw new IllegalStateException("boom"); })
|
||||
.handle((v, ex) -> ex).join();
|
||||
assertInstanceOf(CompletionException.class, seen);
|
||||
assertInstanceOf(IllegalStateException.class, seen.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeExceptionallyIsSeenRawOnTheSameStageAndWrappedDownstream() {
|
||||
CompletableFuture<Integer> f = new CompletableFuture<>();
|
||||
f.completeExceptionally(new IllegalStateException("boom"));
|
||||
assertInstanceOf(IllegalStateException.class, f.handle((v, ex) -> ex).join());
|
||||
assertInstanceOf(CompletionException.class, f.thenApply(x -> x + 1).handle((v, ex) -> ex).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinThrowsCompletionExceptionAndGetThrowsExecutionException() {
|
||||
CompletableFuture<Integer> f = CompletableFuture.failedFuture(new IllegalStateException("boom"));
|
||||
CompletionException ce = assertThrows(CompletionException.class, f::join);
|
||||
ExecutionException ee = assertThrows(ExecutionException.class, f::get);
|
||||
assertInstanceOf(IllegalStateException.class, ce.getCause());
|
||||
assertInstanceOf(IllegalStateException.class, ee.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependentStagesAreSkippedAfterAFailure() {
|
||||
AtomicBoolean ran = new AtomicBoolean();
|
||||
CompletableFuture<Integer> f = CompletableFuture.<Integer>failedFuture(new IllegalStateException("boom"))
|
||||
.thenApply(x -> { ran.set(true); return x + 1; })
|
||||
.thenApply(x -> { ran.set(true); return x * 2; });
|
||||
assertTrue(f.isCompletedExceptionally());
|
||||
assertFalse(ran.get(), "thenApply functions must not run once an earlier stage has failed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCompleteObservesButDoesNotRecover() {
|
||||
AtomicBoolean observed = new AtomicBoolean();
|
||||
CompletableFuture<Integer> f = CompletableFuture.<Integer>failedFuture(new IllegalStateException("boom"))
|
||||
.whenComplete((v, ex) -> observed.set(ex != null));
|
||||
assertTrue(observed.get());
|
||||
assertTrue(f.isCompletedExceptionally());
|
||||
}
|
||||
|
||||
@Test
|
||||
void handleAndExceptionallyRecover() {
|
||||
CompletableFuture<Integer> bad = CompletableFuture.failedFuture(new IllegalStateException("boom"));
|
||||
assertEquals(-1, bad.exceptionally(ex -> -1).join());
|
||||
assertEquals(-2, bad.handle((v, ex) -> ex == null ? v : -2).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionallyComposeRecoversWithAnotherFuture() {
|
||||
int v = CompletableFuture.<Integer>failedFuture(new IllegalStateException("boom"))
|
||||
.exceptionallyCompose(ex -> CompletableFuture.completedFuture(99)).join();
|
||||
assertEquals(99, v);
|
||||
}
|
||||
|
||||
// ---- timeouts and cancellation ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void orTimeoutFailsTheFutureWithTimeoutException() {
|
||||
CompletableFuture<String> f = new CompletableFuture<String>().orTimeout(50, TimeUnit.MILLISECONDS);
|
||||
CompletionException ce = assertThrows(CompletionException.class, f::join);
|
||||
assertInstanceOf(TimeoutException.class, ce.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeOnTimeoutSuppliesTheFallback() {
|
||||
String v = new CompletableFuture<String>().completeOnTimeout("fallback", 50, TimeUnit.MILLISECONDS).join();
|
||||
assertEquals("fallback", v);
|
||||
}
|
||||
|
||||
@Test
|
||||
void orTimeoutDoesNotStopTheRunningTask() throws Exception {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
|
||||
CountDownLatch finished = new CountDownLatch(1);
|
||||
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(300);
|
||||
finished.countDown();
|
||||
return "late";
|
||||
}, pool).orTimeout(50, TimeUnit.MILLISECONDS);
|
||||
assertThrows(CompletionException.class, f::join);
|
||||
assertEquals(1, finished.getCount(), "task should still be running right after the timeout");
|
||||
assertTrue(finished.await(2, TimeUnit.SECONDS), "task should run to completion");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelTrueDoesNotInterruptTheTask() throws Exception {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
|
||||
AtomicBoolean sawInterrupt = new AtomicBoolean();
|
||||
CountDownLatch ran = new CountDownLatch(1);
|
||||
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
Thread.sleep(300);
|
||||
} catch (InterruptedException e) {
|
||||
sawInterrupt.set(true);
|
||||
}
|
||||
ran.countDown();
|
||||
return "x";
|
||||
}, pool);
|
||||
sleep(30);
|
||||
assertTrue(f.cancel(true));
|
||||
assertThrows(CancellationException.class, f::join);
|
||||
assertTrue(ran.await(2, TimeUnit.SECONDS));
|
||||
assertFalse(sawInterrupt.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingTheExecutorFutureDoesInterruptTheTask() throws Exception {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
|
||||
CountDownLatch interrupted = new CountDownLatch(1);
|
||||
Future<?> handle = pool.submit(() -> {
|
||||
try {
|
||||
Thread.sleep(2_000);
|
||||
} catch (InterruptedException e) {
|
||||
interrupted.countDown();
|
||||
}
|
||||
});
|
||||
sleep(30);
|
||||
handle.cancel(true);
|
||||
assertTrue(interrupted.await(1, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- allOf / anyOf ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void allOfWaitsForTheSlowOneEvenAfterAnEarlyFailure() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
|
||||
CompletableFuture<String> early = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(30);
|
||||
throw new IllegalStateException("early");
|
||||
}, pool);
|
||||
AtomicBoolean slowDone = new AtomicBoolean();
|
||||
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(300);
|
||||
slowDone.set(true);
|
||||
return "ok";
|
||||
}, pool);
|
||||
assertThrows(CompletionException.class, () -> CompletableFuture.allOf(early, slow).join());
|
||||
assertTrue(slowDone.get(), "allOf only fails after every input has completed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failFastHelperFailsBeforeTheSlowOneFinishes() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
|
||||
CompletableFuture<String> early = AllOfAnyOfDemo.failAfter(30, pool);
|
||||
AtomicBoolean slowDone = new AtomicBoolean();
|
||||
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
|
||||
sleep(300);
|
||||
slowDone.set(true);
|
||||
return "ok";
|
||||
}, pool);
|
||||
assertThrows(CompletionException.class, () -> AllOfAnyOfDemo.allOrFailFast(List.of(early, slow)).join());
|
||||
assertFalse(slowDone.get(), "the slow task is still running when the helper fails");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anyOfCountsAFailureAsTheFirstCompletion() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
|
||||
CompletableFuture<Object> any = CompletableFuture.anyOf(
|
||||
AllOfAnyOfDemo.failAfter(20, pool), AllOfAnyOfDemo.after(150, "ok", pool));
|
||||
assertThrows(CompletionException.class, any::join);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstSuccessSkipsFailures() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
|
||||
String v = AllOfAnyOfDemo.firstSuccess(List.of(
|
||||
AllOfAnyOfDemo.failAfter(20, pool), AllOfAnyOfDemo.after(100, "ok", pool))).join();
|
||||
assertEquals("ok", v);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstSuccessFailsOnlyWhenEveryInputFails() {
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
|
||||
CompletableFuture<String> f = AllOfAnyOfDemo.firstSuccess(List.of(
|
||||
AllOfAnyOfDemo.failAfter(10, pool), AllOfAnyOfDemo.failAfter(20, pool)));
|
||||
assertThrows(CompletionException.class, f::join);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- virtual threads --------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void virtualThreadExecutorRunsStagesOnVirtualThreads() {
|
||||
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
boolean virtual = CompletableFuture.supplyAsync(() -> Thread.currentThread().isVirtual(), vt).join();
|
||||
assertTrue(virtual);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void manyBlockingTasksFinishInAboutOneTaskTimeOnVirtualThreads() {
|
||||
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
long t0 = System.nanoTime();
|
||||
List<CompletableFuture<Integer>> fs = java.util.stream.IntStream.range(0, 1_000)
|
||||
.mapToObj(i -> CompletableFuture.supplyAsync(() -> { sleep(100); return 1; }, vt)).toList();
|
||||
CompletableFuture.allOf(fs.toArray(CompletableFuture[]::new)).join();
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
assertTrue(ms < 1_500, "1,000 x 100 ms sleeps on virtual threads should not take " + ms + " ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user