forked from krka/futures-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllOfTest.java
85 lines (68 loc) · 2.75 KB
/
AllOfTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package se.krka.futures;
import com.spotify.futures.CompletableFutures;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class AllOfTest {
@Test
public void testAllOfCorrect() {
CompletableFuture<String> futureA = new CompletableFuture<>();
CompletableFuture<String> futureB = new CompletableFuture<>();
CompletableFuture<String> futureC = new CompletableFuture<>();
CompletableFuture<Void> futureAll = CompletableFuture.allOf(futureA, futureB, futureC);
CompletableFuture<String> joined = futureAll.thenApply(aVoid -> futureA.join() + futureB.join() + futureC.join());
futureA.complete("A");
futureB.complete("B");
futureC.complete("C");
assertEquals("ABC", joined.join());
}
@Test
public void testAllOfIncorrect() {
expectTimeout(() -> {
CompletableFuture<String> futureA = new CompletableFuture<>();
CompletableFuture<String> futureB = new CompletableFuture<>();
CompletableFuture<String> futureC = new CompletableFuture<>();
CompletableFuture<String> futureD = new CompletableFuture<>();
// Oops, forgot to include futureD here!
CompletableFuture<Void> futureAll = CompletableFuture.allOf(futureA, futureB, futureC);
CompletableFuture<String> joined = futureAll.thenApply(aVoid -> futureA.join() + futureB.join() + futureC.join() + futureD.join());
futureA.complete("A");
futureB.complete("B");
futureC.complete("C");
// futureAll is complete now, but callback is deadlocked!
joined.join();
});
}
private void expectTimeout(Runnable runnable) {
try {
CompletableFuture<?> future = CompletableFuture.supplyAsync(() -> {
runnable.run();
return null;
});
future.get(1, TimeUnit.SECONDS);
fail("Unexpected success");
} catch (InterruptedException | ExecutionException e) {
fail("Unexpected exception: " + e.getMessage());
} catch (TimeoutException e) {
// Expected
}
}
@Test
public void testBetterApproach() {
CompletableFuture<String> futureA = new CompletableFuture<>();
CompletableFuture<String> futureB = new CompletableFuture<>();
CompletableFuture<String> futureC = new CompletableFuture<>();
CompletionStage<String> futureAll = CompletableFutures.combine(
futureA, futureB, futureC,
(a, b, c) -> a + b + c);
futureA.complete("A");
futureB.complete("B");
futureC.complete("C");
assertEquals("ABC", futureAll.toCompletableFuture().join());
}
}