|
| 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