blob: 39a1f87e3fa467dbbcb1dd48c5e6b7eaa620f94d [file] [log] [blame]
Jordan Halterman9bdc24f2017-04-19 23:45:12 -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.ExecutionException;
21import java.util.concurrent.Executor;
22import java.util.concurrent.TimeUnit;
23import java.util.concurrent.TimeoutException;
24
25import org.junit.Test;
26
27import static org.junit.Assert.assertEquals;
28
29/**
30 * Best effort serial executor test.
31 */
32public class BestEffortSerialExecutorTest {
33
34 @Test
35 public void testSerialExecution() throws Throwable {
36 Executor executor = new BestEffortSerialExecutor(SharedExecutors.getPoolThreadExecutor());
37 CountDownLatch latch = new CountDownLatch(2);
38 executor.execute(latch::countDown);
39 executor.execute(latch::countDown);
40 latch.await();
41 assertEquals(0, latch.getCount());
42 }
43
44 @Test
45 public void testBlockedExecution() throws Throwable {
46 Executor executor = new BestEffortSerialExecutor(SharedExecutors.getPoolThreadExecutor());
47 CountDownLatch latch = new CountDownLatch(3);
48 executor.execute(() -> {
49 try {
50 Thread.sleep(2000);
51 latch.countDown();
52 } catch (InterruptedException e) {
53 }
54 });
55 Thread.sleep(10);
56 executor.execute(() -> {
57 try {
58 new CompletableFuture<>().get(2, TimeUnit.SECONDS);
59 } catch (InterruptedException | ExecutionException | TimeoutException e) {
60 latch.countDown();
61 }
62 });
63 Thread.sleep(10);
64 executor.execute(latch::countDown);
65 latch.await(1, TimeUnit.SECONDS);
66 assertEquals(2, latch.getCount());
67 latch.await(3, TimeUnit.SECONDS);
68 assertEquals(0, latch.getCount());
69 }
70
71}