blob: d3fb450f5b95d923b7a2d64b1ab6bfffde1a2e73 (
plain) (
blame)
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
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bjorncs
*/
class CompletableFuturesTest {
@Test
public void firstof_completes_when_first_futures_has_completed() {
CompletableFuture<String> f1 = new CompletableFuture<>();
CompletableFuture<String> f2 = new CompletableFuture<>();
CompletableFuture<String> f3 = new CompletableFuture<>();
CompletableFuture<String> result = CompletableFutures.firstOf(List.of(f1, f2, f3));
f1.complete("success");
assertTrue(result.isDone());
assertFalse(result.isCompletedExceptionally());
assertEquals("success", result.join());
}
@Test
public void firstof_completes_if_any_futures_completes() {
CompletableFuture<String> f1 = new CompletableFuture<>();
CompletableFuture<String> f2 = new CompletableFuture<>();
CompletableFuture<String> f3 = new CompletableFuture<>();
CompletableFuture<String> result = CompletableFutures.firstOf(List.of(f1, f2, f3));
f1.completeExceptionally(new Throwable("t1"));
f2.completeExceptionally(new Throwable("t2"));
f3.complete("success");
assertTrue(result.isDone());
assertFalse(result.isCompletedExceptionally());
assertEquals("success", result.join());
}
@Test
public void firstof_completes_exceptionally_when_all_futures_have_complete_exceptionally() {
CompletableFuture<String> f1 = new CompletableFuture<>();
CompletableFuture<String> f2 = new CompletableFuture<>();
CompletableFuture<String> f3 = new CompletableFuture<>();
CompletableFuture<String> result = CompletableFutures.firstOf(List.of(f1, f2, f3));
f1.completeExceptionally(new Throwable("t1"));
f2.completeExceptionally(new Throwable("t2"));
f3.completeExceptionally(new Throwable("t3"));
assertTrue(result.isDone());
assertTrue(result.isCompletedExceptionally());
try {
result.join();
fail("Exception expected");
} catch (CompletionException e) {
Throwable cause = e.getCause();
assertEquals("t1", cause.getMessage());
assertEquals(2, cause.getSuppressed().length);
}
}
}
|