Skip to content

Commit d32d3ed

Browse files
jmelo-lyncodepivovarit
authored andcommitted
Java 9 CompletableFuture API Improvements (eugenp#1384)
1 parent b7e74ce commit d32d3ed

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

‎core-java-9/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@
88
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
99
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
1010
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
11+
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package com.baeldung.java9.concurrent.future;
2+
3+
import java.util.concurrent.CompletableFuture;
4+
import java.util.concurrent.ExecutionException;
5+
import java.util.concurrent.TimeUnit;
6+
import java.util.concurrent.TimeoutException;
7+
import static org.junit.Assert.assertFalse;
8+
import static org.junit.Assert.assertSame;
9+
import static org.junit.Assert.assertTrue;
10+
import org.junit.Test;
11+
12+
public class CompletableFutureTest {
13+
@Test
14+
public void testDelay () throws Exception {
15+
Object input = new Object();
16+
CompletableFuture<Object> future = new CompletableFuture<>();
17+
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
18+
19+
Thread.sleep(100);
20+
21+
assertFalse(future.isDone());
22+
23+
Thread.sleep(1000);
24+
assertTrue(future.isDone());
25+
assertSame(input, future.get());
26+
}
27+
28+
@Test
29+
public void testTimeoutTriggered () throws Exception {
30+
CompletableFuture<Object> future = new CompletableFuture<>();
31+
future.orTimeout(1, TimeUnit.SECONDS);
32+
33+
Thread.sleep(1100);
34+
35+
assertTrue(future.isDone());
36+
37+
try {
38+
future.get();
39+
} catch (ExecutionException e) {
40+
assertTrue(e.getCause() instanceof TimeoutException);
41+
}
42+
}
43+
44+
@Test
45+
public void testTimeoutNotTriggered () throws Exception {
46+
Object input = new Object();
47+
CompletableFuture<Object> future = new CompletableFuture<>();
48+
49+
future.orTimeout(1, TimeUnit.SECONDS);
50+
51+
Thread.sleep(100);
52+
53+
future.complete(input);
54+
55+
Thread.sleep(1000);
56+
57+
assertTrue(future.isDone());
58+
assertSame(input, future.get());
59+
}
60+
61+
62+
63+
@Test
64+
public void completeOnTimeout () throws Exception {
65+
Object input = new Object();
66+
CompletableFuture<Object> future = new CompletableFuture<>();
67+
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);
68+
69+
Thread.sleep(1100);
70+
71+
assertTrue(future.isDone());
72+
assertSame(input, future.get());
73+
}
74+
}

0 commit comments

Comments
 (0)