blob: 10acd2adfd2d9c99d6467878b3dd6b45b7a0ef4b [file] [log] [blame]
Brian O'Connorc6713a82015-02-24 11:55:48 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Brian O'Connorc6713a82015-02-24 11:55:48 -08003 *
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 com.google.common.collect.Lists;
19import org.junit.Test;
20
21import java.util.List;
22import java.util.concurrent.CountDownLatch;
23import java.util.concurrent.ExecutionException;
24import java.util.concurrent.ExecutorService;
25import java.util.concurrent.Executors;
26import java.util.concurrent.Future;
27import java.util.concurrent.TimeUnit;
28import java.util.concurrent.atomic.AtomicBoolean;
29
30import static org.junit.Assert.*;
31import static org.onlab.util.BoundedThreadPool.*;
32import static org.onlab.util.Tools.namedThreads;
33
34/**
35 * Test of BoundedThreadPool.
36 */
37public final class BoundedThreadPoolTest {
38
39 @Test
40 public void simpleJob() {
41 final Thread myThread = Thread.currentThread();
42 final AtomicBoolean sameThread = new AtomicBoolean(true);
43 final CountDownLatch latch = new CountDownLatch(1);
44
45 BoundedThreadPool exec = newSingleThreadExecutor(namedThreads("test"));
46 exec.submit(() -> {
47 sameThread.set(myThread.equals(Thread.currentThread()));
48 latch.countDown();
49 });
50
51 try {
52 assertTrue("Job not run", latch.await(100, TimeUnit.MILLISECONDS));
53 assertFalse("Runnable used caller thread", sameThread.get());
54 } catch (InterruptedException e) {
55 fail();
56 } finally {
57 exec.shutdown();
58 }
59
60 // TODO perhaps move to tearDown
61 try {
62 assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS));
63 } catch (InterruptedException e) {
64 fail();
65 }
66 }
67
68 private List<CountDownLatch> fillExecutor(BoundedThreadPool exec) {
69 int numThreads = exec.getMaximumPoolSize();
70 List<CountDownLatch> latches = Lists.newArrayList();
71 final CountDownLatch started = new CountDownLatch(numThreads);
72 List<CountDownLatch> finished = Lists.newArrayList();
73
74 // seed the executor's threads
75 for (int i = 0; i < numThreads; i++) {
76 final CountDownLatch latch = new CountDownLatch(1);
77 final CountDownLatch fin = new CountDownLatch(1);
78 latches.add(latch);
79 finished.add(fin);
80 exec.submit(() -> {
81 try {
82 started.countDown();
83 latch.await();
84 fin.countDown();
85 } catch (InterruptedException e) {
86 fail();
87 }
88 });
89 }
90 try {
91 assertTrue(started.await(100, TimeUnit.MILLISECONDS));
92 } catch (InterruptedException e) {
93 fail();
94 }
95 // fill the queue
96 CountDownLatch startedBlocked = new CountDownLatch(1);
97 while (exec.getQueue().remainingCapacity() > 0) {
98 final CountDownLatch latch = new CountDownLatch(1);
99 latches.add(latch);
100 exec.submit(() -> {
101 try {
102 startedBlocked.countDown();
103 latch.await();
104 } catch (InterruptedException e) {
105 fail();
106 }
107 });
108 }
109
110 latches.remove(0).countDown(); // release one of the executors
111 // ... we need to do this because load is recomputed when jobs are taken
112 // Note: For this to work, 1 / numThreads must be less than the load threshold (0.2)
113
114 // verify that the old job has terminated
115 try {
116 assertTrue("Job didn't finish",
117 finished.remove(0).await(100, TimeUnit.MILLISECONDS));
118 } catch (InterruptedException e) {
119 fail();
120 }
121
122 // verify that a previously blocked thread has started
123 try {
124 assertTrue(startedBlocked.await(10, TimeUnit.MILLISECONDS));
125 } catch (InterruptedException e) {
126 fail();
127 }
128
129
130 // add another job to fill the queue
131 final CountDownLatch latch = new CountDownLatch(1);
132 latches.add(latch);
133 exec.submit(() -> {
134 try {
135 latch.await();
136 } catch (InterruptedException e) {
137 fail();
138 }
139 });
140 assertEquals(exec.getQueue().size(), maxQueueSize);
141
142 return latches;
143 }
144
145 @Test
146 public void releaseOneThread() {
147 maxQueueSize = 10;
148 BoundedThreadPool exec = newFixedThreadPool(4, namedThreads("test"));
149 List<CountDownLatch> latches = fillExecutor(exec);
150
151 CountDownLatch myLatch = new CountDownLatch(1);
152 ExecutorService myExec = Executors.newSingleThreadExecutor();
153 Future<Thread> expected = myExec.submit(Thread::currentThread);
154
155 assertEquals(exec.getQueue().size(), maxQueueSize);
156 long start = System.nanoTime();
157 Future<Thread> actual = myExec.submit(() -> {
158 return exec.submit(() -> {
159 myLatch.countDown();
160 return Thread.currentThread();
161 }).get();
162 });
163
164 try {
165 assertFalse("Thread should still be blocked",
166 myLatch.await(10, TimeUnit.MILLISECONDS));
167
168 latches.remove(0).countDown(); // release the first thread
169 assertFalse("Thread should still be blocked",
170 myLatch.await(10, TimeUnit.MILLISECONDS));
171 latches.remove(0).countDown(); // release the second thread
172
173 assertTrue("Thread should be unblocked",
Brian O'Connorf32da3b2016-05-05 16:22:52 -0700174 myLatch.await(1, TimeUnit.SECONDS));
Brian O'Connorc6713a82015-02-24 11:55:48 -0800175 long delta = System.nanoTime() - start;
176 double load = exec.getQueue().size() / (double) maxQueueSize;
177 assertTrue("Load is greater than threshold", load <= 0.8);
178 assertTrue("Load is less than threshold", load >= 0.6);
179 assertEquals("Work done on wrong thread", expected.get(), actual.get());
180 assertTrue("Took more than one second", delta < Math.pow(10, 9));
181 } catch (InterruptedException | ExecutionException e) {
182 fail();
183 } finally {
184 latches.forEach(CountDownLatch::countDown);
185 exec.shutdown();
186 }
187
188 // TODO perhaps move to tearDown
189 try {
190 assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS));
191 } catch (InterruptedException e) {
192 fail();
193 }
194
195 }
196
197 @Test
198 public void highLoadTimeout() {
199 maxQueueSize = 10;
200 BoundedThreadPool exec = newFixedThreadPool(2, namedThreads("test"));
201 List<CountDownLatch> latches = fillExecutor(exec);
202
203 // true if the job is executed and it is done on the test thread
204 final AtomicBoolean sameThread = new AtomicBoolean(false);
205 final Thread myThread = Thread.currentThread();
206 long start = System.nanoTime();
207 exec.submit(() -> {
208 sameThread.set(myThread.equals(Thread.currentThread()));
209 });
210
211 long delta = System.nanoTime() - start;
212 assertEquals(maxQueueSize, exec.getQueue().size());
213 assertTrue("Work done on wrong thread (or didn't happen)", sameThread.get());
214 assertTrue("Took less than one second. Actual: " + delta / 1_000_000.0 + "ms",
215 delta > Math.pow(10, 9));
216 assertTrue("Took more than two seconds", delta < 2 * Math.pow(10, 9));
217 latches.forEach(CountDownLatch::countDown);
218 exec.shutdown();
219
220 // TODO perhaps move to tearDown
221 try {
222 assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS));
223 } catch (InterruptedException e) {
224 fail();
225 }
226 }
227}