blob: 6a72b582477aaf94deb1489c229ba149e24f8550 [file] [log] [blame]
Jordan Halterman046faeb2017-05-01 15:10:13 -07001/*
2 * Copyright 2017-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.util;
17
18import java.util.concurrent.CompletableFuture;
19import java.util.concurrent.CountDownLatch;
20import java.util.concurrent.Executor;
21import java.util.concurrent.TimeUnit;
22
23import org.junit.Test;
24
25import static org.junit.Assert.assertEquals;
26import static org.junit.Assert.assertFalse;
27import static org.junit.Assert.assertTrue;
28
29/**
30 * Blocking-aware future test.
31 */
32public class BlockingAwareFutureTest {
33
34 /**
35 * Tests normal callback execution.
36 */
37 @Test
38 public void testNonBlockingThread() throws Exception {
39 CompletableFuture<String> future = new CompletableFuture<>();
40 Executor executor = SharedExecutors.getPoolThreadExecutor();
41 BlockingAwareFuture<String> blockingFuture =
42 (BlockingAwareFuture<String>) Tools.orderedFuture(future, new OrderedExecutor(executor), executor);
43 CountDownLatch latch = new CountDownLatch(1);
44 blockingFuture.thenRun(() -> latch.countDown());
45 executor.execute(() -> future.complete("foo"));
46 latch.await(5, TimeUnit.SECONDS);
47 assertEquals(0, latch.getCount());
48 assertEquals("foo", blockingFuture.join());
49 assertFalse(blockingFuture.isBlocked());
50 }
51
52 /**
53 * Tests blocking an ordered thread.
54 */
55 @Test
56 public void testBlockingThread() throws Exception {
57 CompletableFuture<String> future = new CompletableFuture<>();
58 Executor executor = SharedExecutors.getPoolThreadExecutor();
59 BlockingAwareFuture<String> blockingFuture =
60 (BlockingAwareFuture<String>) Tools.orderedFuture(future, new OrderedExecutor(executor), executor);
61 CountDownLatch latch = new CountDownLatch(2);
62 CompletableFuture<String> wrappedFuture = blockingFuture.thenApply(v -> {
63 assertEquals("foo", v);
64 latch.countDown();
65 return v;
66 });
67 wrappedFuture.thenRun(() -> latch.countDown());
68 executor.execute(() -> wrappedFuture.join());
69 Thread.sleep(100);
70 assertTrue(blockingFuture.isBlocked());
71 future.complete("foo");
72 latch.await(5, TimeUnit.SECONDS);
73 assertEquals(0, latch.getCount());
74 assertEquals("foo", blockingFuture.join());
75 assertEquals("foo", wrappedFuture.join());
76 assertFalse(blockingFuture.isBlocked());
77 }
78
79}