[cvs] / jsr166 / src / test / tck / ScheduledExecutorTest.java Repository:
ViewVC logotype

Annotation of /jsr166/src/test/tck/ScheduledExecutorTest.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.95 - (view) (download)

1 : dl 1.1 /*
2 : dl 1.13 * Written by Doug Lea with assistance from members of JCP JSR-166
3 :     * Expert Group and released to the public domain, as explained at
4 : jsr166 1.37 * http://creativecommons.org/publicdomain/zero/1.0/
5 : jsr166 1.22 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 :     * Pat Fisher, Mike Judd.
7 : dl 1.1 */
8 :    
9 : jsr166 1.25 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 : jsr166 1.80 import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 : jsr166 1.54 import static java.util.concurrent.TimeUnit.SECONDS;
12 : jsr166 1.50
13 :     import java.util.ArrayList;
14 : jsr166 1.94 import java.util.Collection;
15 :     import java.util.Collections;
16 : jsr166 1.54 import java.util.HashSet;
17 : jsr166 1.50 import java.util.List;
18 :     import java.util.concurrent.BlockingQueue;
19 :     import java.util.concurrent.Callable;
20 : jsr166 1.52 import java.util.concurrent.CancellationException;
21 : jsr166 1.50 import java.util.concurrent.CountDownLatch;
22 :     import java.util.concurrent.ExecutionException;
23 :     import java.util.concurrent.ExecutorService;
24 :     import java.util.concurrent.Future;
25 :     import java.util.concurrent.RejectedExecutionException;
26 :     import java.util.concurrent.ScheduledFuture;
27 :     import java.util.concurrent.ScheduledThreadPoolExecutor;
28 :     import java.util.concurrent.ThreadFactory;
29 : jsr166 1.88 import java.util.concurrent.ThreadLocalRandom;
30 : jsr166 1.50 import java.util.concurrent.ThreadPoolExecutor;
31 : jsr166 1.80 import java.util.concurrent.atomic.AtomicBoolean;
32 : jsr166 1.46 import java.util.concurrent.atomic.AtomicInteger;
33 : jsr166 1.80 import java.util.concurrent.atomic.AtomicLong;
34 : jsr166 1.89 import java.util.stream.Stream;
35 : dl 1.1
36 : jsr166 1.50 import junit.framework.Test;
37 :     import junit.framework.TestSuite;
38 :    
39 : dl 1.4 public class ScheduledExecutorTest extends JSR166TestCase {
40 : dl 1.1 public static void main(String[] args) {
41 : jsr166 1.51 main(suite(), args);
42 : dl 1.1 }
43 :     public static Test suite() {
44 : jsr166 1.26 return new TestSuite(ScheduledExecutorTest.class);
45 : dl 1.1 }
46 :    
47 : dl 1.5 /**
48 : dl 1.6 * execute successfully executes a runnable
49 : dl 1.5 */
50 : jsr166 1.25 public void testExecute() throws InterruptedException {
51 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
52 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
53 :     final CountDownLatch done = new CountDownLatch(1);
54 :     final Runnable task = new CheckedRunnable() {
55 :     public void realRun() { done.countDown(); }};
56 : jsr166 1.33 p.execute(task);
57 : jsr166 1.86 await(done);
58 : jsr166 1.33 }
59 : dl 1.1 }
60 :    
61 : dl 1.5 /**
62 : dl 1.6 * delayed schedule of callable successfully executes after delay
63 : dl 1.5 */
64 : jsr166 1.25 public void testSchedule1() throws Exception {
65 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
66 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
67 :     final long startTime = System.nanoTime();
68 :     final CountDownLatch done = new CountDownLatch(1);
69 : jsr166 1.33 Callable task = new CheckedCallable<Boolean>() {
70 :     public Boolean realCall() {
71 :     done.countDown();
72 : jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
73 : jsr166 1.33 return Boolean.TRUE;
74 :     }};
75 : jsr166 1.44 Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
76 :     assertSame(Boolean.TRUE, f.get());
77 :     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
78 : jsr166 1.93 assertEquals(0L, done.getCount());
79 : jsr166 1.33 }
80 : dl 1.1 }
81 :    
82 :     /**
83 : jsr166 1.32 * delayed schedule of runnable successfully executes after delay
84 : dl 1.1 */
85 : jsr166 1.33 public void testSchedule3() throws Exception {
86 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
87 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
88 :     final long startTime = System.nanoTime();
89 :     final CountDownLatch done = new CountDownLatch(1);
90 : jsr166 1.33 Runnable task = new CheckedRunnable() {
91 :     public void realRun() {
92 :     done.countDown();
93 : jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
94 : jsr166 1.33 }};
95 : jsr166 1.44 Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
96 :     await(done);
97 :     assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
98 :     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
99 : jsr166 1.33 }
100 : dl 1.1 }
101 : jsr166 1.22
102 : dl 1.1 /**
103 : dl 1.6 * scheduleAtFixedRate executes runnable after given initial delay
104 : dl 1.1 */
105 : jsr166 1.33 public void testSchedule4() throws Exception {
106 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
107 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
108 :     final long startTime = System.nanoTime();
109 :     final CountDownLatch done = new CountDownLatch(1);
110 : jsr166 1.33 Runnable task = new CheckedRunnable() {
111 :     public void realRun() {
112 :     done.countDown();
113 : jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
114 : jsr166 1.33 }};
115 :     ScheduledFuture f =
116 : jsr166 1.44 p.scheduleAtFixedRate(task, timeoutMillis(),
117 :     LONG_DELAY_MS, MILLISECONDS);
118 :     await(done);
119 :     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
120 : jsr166 1.33 f.cancel(true);
121 :     }
122 : dl 1.18 }
123 :    
124 : dl 1.6 /**
125 :     * scheduleWithFixedDelay executes runnable after given initial delay
126 :     */
127 : jsr166 1.44 public void testSchedule5() throws Exception {
128 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
129 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
130 :     final long startTime = System.nanoTime();
131 :     final CountDownLatch done = new CountDownLatch(1);
132 : jsr166 1.33 Runnable task = new CheckedRunnable() {
133 :     public void realRun() {
134 :     done.countDown();
135 : jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
136 : jsr166 1.33 }};
137 :     ScheduledFuture f =
138 : jsr166 1.44 p.scheduleWithFixedDelay(task, timeoutMillis(),
139 :     LONG_DELAY_MS, MILLISECONDS);
140 :     await(done);
141 :     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
142 : jsr166 1.33 f.cancel(true);
143 :     }
144 :     }
145 :    
146 :     static class RunnableCounter implements Runnable {
147 :     AtomicInteger count = new AtomicInteger(0);
148 :     public void run() { count.getAndIncrement(); }
149 : dl 1.1 }
150 : jsr166 1.22
151 : dl 1.6 /**
152 : jsr166 1.80 * scheduleAtFixedRate executes series of tasks at given rate.
153 :     * Eventually, it must hold that:
154 :     * cycles - 1 <= elapsedMillis/delay < cycles
155 : dl 1.18 */
156 : jsr166 1.25 public void testFixedRateSequence() throws InterruptedException {
157 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
158 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
159 : jsr166 1.47 for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
160 : jsr166 1.80 final long startTime = System.nanoTime();
161 :     final int cycles = 8;
162 : jsr166 1.47 final CountDownLatch done = new CountDownLatch(cycles);
163 : jsr166 1.80 final Runnable task = new CheckedRunnable() {
164 : jsr166 1.47 public void realRun() { done.countDown(); }};
165 : jsr166 1.80 final ScheduledFuture periodicTask =
166 : jsr166 1.47 p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
167 : jsr166 1.80 final int totalDelayMillis = (cycles - 1) * delay;
168 :     await(done, totalDelayMillis + LONG_DELAY_MS);
169 : jsr166 1.79 periodicTask.cancel(true);
170 : jsr166 1.80 final long elapsedMillis = millisElapsedSince(startTime);
171 :     assertTrue(elapsedMillis >= totalDelayMillis);
172 :     if (elapsedMillis <= cycles * delay)
173 : jsr166 1.47 return;
174 : jsr166 1.80 // else retry with longer delay
175 : jsr166 1.47 }
176 : jsr166 1.78 fail("unexpected execution rate");
177 : jsr166 1.47 }
178 : dl 1.18 }
179 :    
180 :     /**
181 : jsr166 1.80 * scheduleWithFixedDelay executes series of tasks with given period.
182 :     * Eventually, it must hold that each task starts at least delay and at
183 :     * most 2 * delay after the termination of the previous task.
184 : dl 1.18 */
185 : jsr166 1.25 public void testFixedDelaySequence() throws InterruptedException {
186 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
187 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
188 : jsr166 1.47 for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
189 : jsr166 1.80 final long startTime = System.nanoTime();
190 :     final AtomicLong previous = new AtomicLong(startTime);
191 :     final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
192 :     final int cycles = 8;
193 : jsr166 1.47 final CountDownLatch done = new CountDownLatch(cycles);
194 : jsr166 1.80 final int d = delay;
195 :     final Runnable task = new CheckedRunnable() {
196 :     public void realRun() {
197 :     long now = System.nanoTime();
198 :     long elapsedMillis
199 :     = NANOSECONDS.toMillis(now - previous.get());
200 :     if (done.getCount() == cycles) { // first execution
201 :     if (elapsedMillis >= d)
202 :     tryLongerDelay.set(true);
203 :     } else {
204 :     assertTrue(elapsedMillis >= d);
205 :     if (elapsedMillis >= 2 * d)
206 :     tryLongerDelay.set(true);
207 :     }
208 :     previous.set(now);
209 :     done.countDown();
210 :     }};
211 :     final ScheduledFuture periodicTask =
212 : jsr166 1.47 p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
213 : jsr166 1.80 final int totalDelayMillis = (cycles - 1) * delay;
214 :     await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
215 : jsr166 1.79 periodicTask.cancel(true);
216 : jsr166 1.80 final long elapsedMillis = millisElapsedSince(startTime);
217 :     assertTrue(elapsedMillis >= totalDelayMillis);
218 :     if (!tryLongerDelay.get())
219 : jsr166 1.47 return;
220 : jsr166 1.80 // else retry with longer delay
221 : jsr166 1.47 }
222 : jsr166 1.78 fail("unexpected execution rate");
223 : jsr166 1.47 }
224 : dl 1.18 }
225 :    
226 :     /**
227 : jsr166 1.95 * Submitting null tasks throws NullPointerException
228 : dl 1.6 */
229 : jsr166 1.95 public void testNullTaskSubmission() {
230 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
231 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
232 : jsr166 1.95 assertNullTaskSubmissionThrowsNullPointerException(p);
233 : jsr166 1.62 }
234 : dl 1.6 }
235 :    
236 :     /**
237 : jsr166 1.95 * Submitted tasks are rejected when shutdown
238 : dl 1.6 */
239 : jsr166 1.95 public void testSubmittedTasksRejectedWhenShutdown() throws InterruptedException {
240 : jsr166 1.62 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
241 : jsr166 1.95 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
242 :     final CountDownLatch threadsStarted = new CountDownLatch(p.getCorePoolSize());
243 :     final CountDownLatch done = new CountDownLatch(1);
244 :     final Runnable r = () -> {
245 :     threadsStarted.countDown();
246 :     for (;;) {
247 :     try {
248 :     done.await();
249 :     return;
250 :     } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
251 :     }};
252 :     final Callable<Boolean> c = () -> {
253 :     threadsStarted.countDown();
254 :     for (;;) {
255 :     try {
256 :     done.await();
257 :     return Boolean.TRUE;
258 :     } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
259 :     }};
260 : jsr166 1.22
261 : jsr166 1.95 try (PoolCleaner cleaner = cleaner(p, done)) {
262 :     for (int i = p.getCorePoolSize(); i--> 0; ) {
263 :     switch (rnd.nextInt(4)) {
264 :     case 0: p.execute(r); break;
265 :     case 1: assertFalse(p.submit(r).isDone()); break;
266 :     case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
267 :     case 3: assertFalse(p.submit(c).isDone()); break;
268 :     }
269 :     }
270 : dl 1.1
271 : jsr166 1.95 // ScheduledThreadPoolExecutor has an unbounded queue, so never saturated.
272 :     await(threadsStarted);
273 : dl 1.1
274 : jsr166 1.95 if (rnd.nextBoolean())
275 :     p.shutdownNow();
276 :     else
277 : jsr166 1.62 p.shutdown();
278 : jsr166 1.95 // Pool is shutdown, but not yet terminated
279 :     assertTaskSubmissionsAreRejected(p);
280 :     assertFalse(p.isTerminated());
281 : dl 1.1
282 : jsr166 1.95 done.countDown(); // release blocking tasks
283 :     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
284 : jsr166 1.22
285 : jsr166 1.95 assertTaskSubmissionsAreRejected(p);
286 : jsr166 1.22 }
287 : jsr166 1.95 assertEquals(p.getCorePoolSize(), p.getCompletedTaskCount());
288 : dl 1.1 }
289 :    
290 :     /**
291 : jsr166 1.32 * getActiveCount increases but doesn't overestimate, when a
292 :     * thread becomes active
293 : dl 1.2 */
294 : jsr166 1.25 public void testGetActiveCount() throws InterruptedException {
295 : jsr166 1.73 final CountDownLatch done = new CountDownLatch(1);
296 : jsr166 1.33 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
297 : jsr166 1.73 try (PoolCleaner cleaner = cleaner(p, done)) {
298 : jsr166 1.62 final CountDownLatch threadStarted = new CountDownLatch(1);
299 : jsr166 1.33 assertEquals(0, p.getActiveCount());
300 :     p.execute(new CheckedRunnable() {
301 :     public void realRun() throws InterruptedException {
302 :     threadStarted.countDown();
303 :     assertEquals(1, p.getActiveCount());
304 : jsr166 1.70 await(done);
305 : jsr166 1.33 }});
306 : jsr166 1.72 await(threadStarted);
307 : jsr166 1.33 assertEquals(1, p.getActiveCount());
308 :     }
309 : dl 1.2 }
310 : jsr166 1.22
311 : dl 1.2 /**
312 : jsr166 1.32 * getCompletedTaskCount increases, but doesn't overestimate,
313 :     * when tasks complete
314 : dl 1.2 */
315 : jsr166 1.25 public void testGetCompletedTaskCount() throws InterruptedException {
316 : jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
317 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
318 :     final CountDownLatch threadStarted = new CountDownLatch(1);
319 :     final CountDownLatch threadProceed = new CountDownLatch(1);
320 :     final CountDownLatch threadDone = new CountDownLatch(1);
321 : jsr166 1.33 assertEquals(0, p.getCompletedTaskCount());
322 :     p.execute(new CheckedRunnable() {
323 :     public void realRun() throws InterruptedException {
324 :     threadStarted.countDown();
325 :     assertEquals(0, p.getCompletedTaskCount());
326 : jsr166 1.86 await(threadProceed);
327 : jsr166 1.33 threadDone.countDown();
328 :     }});
329 : jsr166 1.45 await(threadStarted);
330 : jsr166 1.33 assertEquals(0, p.getCompletedTaskCount());
331 :     threadProceed.countDown();
332 : jsr166 1.86 await(threadDone);
333 : jsr166 1.44 long startTime = System.nanoTime();
334 :     while (p.getCompletedTaskCount() != 1) {
335 :     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
336 :     fail("timed out");
337 :     Thread.yield();
338 :     }
339 : jsr166 1.33 }
340 : dl 1.2 }
341 : jsr166 1.22
342 : dl 1.2 /**
343 : jsr166 1.32 * getCorePoolSize returns size given in constructor if not otherwise set
344 : dl 1.2 */
345 : jsr166 1.25 public void testGetCorePoolSize() throws InterruptedException {
346 : jsr166 1.33 ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
347 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
348 :     assertEquals(1, p.getCorePoolSize());
349 :     }
350 : dl 1.2 }
351 : jsr166 1.22
352 : dl 1.2 /**
353 : jsr166 1.32 * getLargestPoolSize increases, but doesn't overestimate, when
354 :     * multiple threads active
355 : dl 1.2 */
356 : jsr166 1.25 public void testGetLargestPoolSize() throws InterruptedException {
357 : jsr166 1.33 final int THREADS = 3;
358 :     final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
359 :     final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
360 :     final CountDownLatch done = new CountDownLatch(1);
361 : jsr166 1.71 try (PoolCleaner cleaner = cleaner(p, done)) {
362 : jsr166 1.33 assertEquals(0, p.getLargestPoolSize());
363 :     for (int i = 0; i < THREADS; i++)
364 :     p.execute(new CheckedRunnable() {
365 :     public void realRun() throws InterruptedException {
366 :     threadsStarted.countDown();
367 : jsr166 1.70 await(done);
368 : jsr166 1.33 assertEquals(THREADS, p.getLargestPoolSize());
369 :     }});
370 : jsr166 1.71 await(threadsStarted);
371 : jsr166 1.33 assertEquals(THREADS, p.getLargestPoolSize());
372 :     }
373 : jsr166 1.62 assertEquals(THREADS, p.getLargestPoolSize());
374 : dl 1.2 }
375 : jsr166 1.22
376 : dl 1.2 /**
377 : jsr166 1.32 * getPoolSize increases, but doesn't overestimate, when threads
378 :     * become active
379 : dl 1.2 */
380 : jsr166 1.25 public void testGetPoolSize() throws InterruptedException {
381 : jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
382 :     final CountDownLatch threadStarted = new CountDownLatch(1);
383 :     final CountDownLatch done = new CountDownLatch(1);
384 : jsr166 1.71 try (PoolCleaner cleaner = cleaner(p, done)) {
385 : jsr166 1.33 assertEquals(0, p.getPoolSize());
386 :     p.execute(new CheckedRunnable() {
387 :     public void realRun() throws InterruptedException {
388 :     threadStarted.countDown();
389 :     assertEquals(1, p.getPoolSize());
390 : jsr166 1.70 await(done);
391 : jsr166 1.33 }});
392 : jsr166 1.71 await(threadStarted);
393 : jsr166 1.33 assertEquals(1, p.getPoolSize());
394 :     }
395 : dl 1.2 }
396 : jsr166 1.22
397 : dl 1.2 /**
398 : jsr166 1.32 * getTaskCount increases, but doesn't overestimate, when tasks
399 :     * submitted
400 : dl 1.2 */
401 : jsr166 1.25 public void testGetTaskCount() throws InterruptedException {
402 : jsr166 1.65 final int TASKS = 3;
403 :     final CountDownLatch done = new CountDownLatch(1);
404 : jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
405 : jsr166 1.65 try (PoolCleaner cleaner = cleaner(p, done)) {
406 : jsr166 1.62 final CountDownLatch threadStarted = new CountDownLatch(1);
407 : jsr166 1.33 assertEquals(0, p.getTaskCount());
408 : jsr166 1.65 assertEquals(0, p.getCompletedTaskCount());
409 :     p.execute(new CheckedRunnable() {
410 :     public void realRun() throws InterruptedException {
411 :     threadStarted.countDown();
412 : jsr166 1.70 await(done);
413 : jsr166 1.65 }});
414 : jsr166 1.72 await(threadStarted);
415 : jsr166 1.65 assertEquals(1, p.getTaskCount());
416 :     assertEquals(0, p.getCompletedTaskCount());
417 :     for (int i = 0; i < TASKS; i++) {
418 :     assertEquals(1 + i, p.getTaskCount());
419 : jsr166 1.33 p.execute(new CheckedRunnable() {
420 :     public void realRun() throws InterruptedException {
421 :     threadStarted.countDown();
422 : jsr166 1.65 assertEquals(1 + TASKS, p.getTaskCount());
423 : jsr166 1.70 await(done);
424 : jsr166 1.33 }});
425 : jsr166 1.65 }
426 :     assertEquals(1 + TASKS, p.getTaskCount());
427 :     assertEquals(0, p.getCompletedTaskCount());
428 : jsr166 1.33 }
429 : jsr166 1.65 assertEquals(1 + TASKS, p.getTaskCount());
430 :     assertEquals(1 + TASKS, p.getCompletedTaskCount());
431 : dl 1.2 }
432 : dl 1.8
433 : jsr166 1.22 /**
434 : dl 1.8 * getThreadFactory returns factory in constructor if not set
435 :     */
436 : jsr166 1.25 public void testGetThreadFactory() throws InterruptedException {
437 : jsr166 1.63 final ThreadFactory threadFactory = new SimpleThreadFactory();
438 :     final ScheduledThreadPoolExecutor p =
439 :     new ScheduledThreadPoolExecutor(1, threadFactory);
440 :     try (PoolCleaner cleaner = cleaner(p)) {
441 :     assertSame(threadFactory, p.getThreadFactory());
442 :     }
443 : dl 1.8 }
444 :    
445 : jsr166 1.22 /**
446 : dl 1.8 * setThreadFactory sets the thread factory returned by getThreadFactory
447 :     */
448 : jsr166 1.25 public void testSetThreadFactory() throws InterruptedException {
449 : jsr166 1.62 ThreadFactory threadFactory = new SimpleThreadFactory();
450 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
451 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
452 :     p.setThreadFactory(threadFactory);
453 :     assertSame(threadFactory, p.getThreadFactory());
454 :     }
455 : dl 1.8 }
456 :    
457 : jsr166 1.22 /**
458 : dl 1.8 * setThreadFactory(null) throws NPE
459 :     */
460 : jsr166 1.25 public void testSetThreadFactoryNull() throws InterruptedException {
461 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
462 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
463 :     try {
464 :     p.setThreadFactory(null);
465 :     shouldThrow();
466 :     } catch (NullPointerException success) {}
467 : dl 1.8 }
468 :     }
469 : jsr166 1.22
470 : dl 1.2 /**
471 : jsr166 1.85 * The default rejected execution handler is AbortPolicy.
472 :     */
473 :     public void testDefaultRejectedExecutionHandler() {
474 :     final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
475 :     try (PoolCleaner cleaner = cleaner(p)) {
476 :     assertTrue(p.getRejectedExecutionHandler()
477 :     instanceof ThreadPoolExecutor.AbortPolicy);
478 :     }
479 :     }
480 :    
481 :     /**
482 : jsr166 1.41 * isShutdown is false before shutdown, true after
483 : dl 1.2 */
484 : dl 1.5 public void testIsShutdown() {
485 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
486 : jsr166 1.82 assertFalse(p.isShutdown());
487 :     try (PoolCleaner cleaner = cleaner(p)) {
488 :     try {
489 :     p.shutdown();
490 :     assertTrue(p.isShutdown());
491 :     } catch (SecurityException ok) {}
492 : dl 1.2 }
493 :     }
494 :    
495 :     /**
496 : jsr166 1.32 * isTerminated is false before termination, true after
497 : dl 1.2 */
498 : jsr166 1.25 public void testIsTerminated() throws InterruptedException {
499 : jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
500 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
501 :     final CountDownLatch threadStarted = new CountDownLatch(1);
502 :     final CountDownLatch done = new CountDownLatch(1);
503 :     assertFalse(p.isTerminated());
504 : jsr166 1.33 p.execute(new CheckedRunnable() {
505 :     public void realRun() throws InterruptedException {
506 : jsr166 1.36 assertFalse(p.isTerminated());
507 : jsr166 1.33 threadStarted.countDown();
508 : jsr166 1.70 await(done);
509 : jsr166 1.33 }});
510 : jsr166 1.72 await(threadStarted);
511 : jsr166 1.36 assertFalse(p.isTerminating());
512 : jsr166 1.33 done.countDown();
513 :     try { p.shutdown(); } catch (SecurityException ok) { return; }
514 : jsr166 1.62 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
515 :     assertTrue(p.isTerminated());
516 : dl 1.2 }
517 : dl 1.5 }
518 :    
519 :     /**
520 : jsr166 1.32 * isTerminating is not true when running or when terminated
521 : dl 1.5 */
522 : jsr166 1.25 public void testIsTerminating() throws InterruptedException {
523 : jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
524 :     final CountDownLatch threadStarted = new CountDownLatch(1);
525 :     final CountDownLatch done = new CountDownLatch(1);
526 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(p)) {
527 : jsr166 1.33 assertFalse(p.isTerminating());
528 :     p.execute(new CheckedRunnable() {
529 :     public void realRun() throws InterruptedException {
530 : jsr166 1.35 assertFalse(p.isTerminating());
531 : jsr166 1.33 threadStarted.countDown();
532 : jsr166 1.70 await(done);
533 : jsr166 1.33 }});
534 : jsr166 1.72 await(threadStarted);
535 : jsr166 1.33 assertFalse(p.isTerminating());
536 :     done.countDown();
537 :     try { p.shutdown(); } catch (SecurityException ok) { return; }
538 : jsr166 1.62 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
539 :     assertTrue(p.isTerminated());
540 :     assertFalse(p.isTerminating());
541 : jsr166 1.33 }
542 : dl 1.2 }
543 :    
544 :     /**
545 : dl 1.8 * getQueue returns the work queue, which contains queued tasks
546 :     */
547 : jsr166 1.25 public void testGetQueue() throws InterruptedException {
548 : jsr166 1.73 final CountDownLatch done = new CountDownLatch(1);
549 :     final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
550 :     try (PoolCleaner cleaner = cleaner(p, done)) {
551 : jsr166 1.62 final CountDownLatch threadStarted = new CountDownLatch(1);
552 : jsr166 1.33 ScheduledFuture[] tasks = new ScheduledFuture[5];
553 :     for (int i = 0; i < tasks.length; i++) {
554 :     Runnable r = new CheckedRunnable() {
555 :     public void realRun() throws InterruptedException {
556 :     threadStarted.countDown();
557 : jsr166 1.70 await(done);
558 : jsr166 1.33 }};
559 :     tasks[i] = p.schedule(r, 1, MILLISECONDS);
560 :     }
561 : jsr166 1.72 await(threadStarted);
562 : jsr166 1.33 BlockingQueue<Runnable> q = p.getQueue();
563 :     assertTrue(q.contains(tasks[tasks.length - 1]));
564 : dl 1.8 assertFalse(q.contains(tasks[0]));
565 :     }
566 :     }
567 :    
568 :     /**
569 :     * remove(task) removes queued task, and fails to remove active task
570 :     */
571 : jsr166 1.25 public void testRemove() throws InterruptedException {
572 : jsr166 1.73 final CountDownLatch done = new CountDownLatch(1);
573 : jsr166 1.33 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
574 : jsr166 1.73 try (PoolCleaner cleaner = cleaner(p, done)) {
575 : jsr166 1.62 ScheduledFuture[] tasks = new ScheduledFuture[5];
576 :     final CountDownLatch threadStarted = new CountDownLatch(1);
577 : jsr166 1.33 for (int i = 0; i < tasks.length; i++) {
578 :     Runnable r = new CheckedRunnable() {
579 :     public void realRun() throws InterruptedException {
580 :     threadStarted.countDown();
581 : jsr166 1.70 await(done);
582 : jsr166 1.33 }};
583 :     tasks[i] = p.schedule(r, 1, MILLISECONDS);
584 :     }
585 : jsr166 1.72 await(threadStarted);
586 : jsr166 1.33 BlockingQueue<Runnable> q = p.getQueue();
587 :     assertFalse(p.remove((Runnable)tasks[0]));
588 : dl 1.8 assertTrue(q.contains((Runnable)tasks[4]));
589 :     assertTrue(q.contains((Runnable)tasks[3]));
590 : jsr166 1.33 assertTrue(p.remove((Runnable)tasks[4]));
591 :     assertFalse(p.remove((Runnable)tasks[4]));
592 : dl 1.8 assertFalse(q.contains((Runnable)tasks[4]));
593 :     assertTrue(q.contains((Runnable)tasks[3]));
594 : jsr166 1.33 assertTrue(p.remove((Runnable)tasks[3]));
595 : dl 1.8 assertFalse(q.contains((Runnable)tasks[3]));
596 :     }
597 :     }
598 :    
599 :     /**
600 : jsr166 1.40 * purge eventually removes cancelled tasks from the queue
601 : dl 1.2 */
602 : jsr166 1.25 public void testPurge() throws InterruptedException {
603 : jsr166 1.66 final ScheduledFuture[] tasks = new ScheduledFuture[5];
604 :     final Runnable releaser = new Runnable() { public void run() {
605 :     for (ScheduledFuture task : tasks)
606 :     if (task != null) task.cancel(true); }};
607 :     final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
608 :     try (PoolCleaner cleaner = cleaner(p, releaser)) {
609 :     for (int i = 0; i < tasks.length; i++)
610 :     tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
611 :     LONG_DELAY_MS, MILLISECONDS);
612 : jsr166 1.33 int max = tasks.length;
613 : dl 1.19 if (tasks[4].cancel(true)) --max;
614 :     if (tasks[3].cancel(true)) --max;
615 :     // There must eventually be an interference-free point at
616 :     // which purge will not fail. (At worst, when queue is empty.)
617 : jsr166 1.40 long startTime = System.nanoTime();
618 :     do {
619 : jsr166 1.33 p.purge();
620 :     long count = p.getTaskCount();
621 : jsr166 1.40 if (count == max)
622 :     return;
623 : jsr166 1.66 } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
624 : jsr166 1.40 fail("Purge failed to remove cancelled tasks");
625 : dl 1.2 }
626 :     }
627 :    
628 :     /**
629 : jsr166 1.53 * shutdownNow returns a list containing tasks that were not run,
630 :     * and those tasks are drained from the queue
631 : dl 1.2 */
632 : jsr166 1.56 public void testShutdownNow() throws InterruptedException {
633 :     final int poolSize = 2;
634 :     final int count = 5;
635 :     final AtomicInteger ran = new AtomicInteger(0);
636 :     final ScheduledThreadPoolExecutor p =
637 :     new ScheduledThreadPoolExecutor(poolSize);
638 : jsr166 1.64 final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
639 : jsr166 1.58 Runnable waiter = new CheckedRunnable() { public void realRun() {
640 : jsr166 1.56 threadsStarted.countDown();
641 :     try {
642 :     MILLISECONDS.sleep(2 * LONG_DELAY_MS);
643 :     } catch (InterruptedException success) {}
644 :     ran.getAndIncrement();
645 :     }};
646 :     for (int i = 0; i < count; i++)
647 :     p.execute(waiter);
648 : jsr166 1.71 await(threadsStarted);
649 : jsr166 1.57 assertEquals(poolSize, p.getActiveCount());
650 :     assertEquals(0, p.getCompletedTaskCount());
651 : jsr166 1.56 final List<Runnable> queuedTasks;
652 :     try {
653 :     queuedTasks = p.shutdownNow();
654 :     } catch (SecurityException ok) {
655 :     return; // Allowed in case test doesn't have privs
656 :     }
657 :     assertTrue(p.isShutdown());
658 :     assertTrue(p.getQueue().isEmpty());
659 :     assertEquals(count - poolSize, queuedTasks.size());
660 :     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
661 :     assertTrue(p.isTerminated());
662 :     assertEquals(poolSize, ran.get());
663 : jsr166 1.57 assertEquals(poolSize, p.getCompletedTaskCount());
664 : jsr166 1.56 }
665 :    
666 :     /**
667 :     * shutdownNow returns a list containing tasks that were not run,
668 :     * and those tasks are drained from the queue
669 :     */
670 : jsr166 1.54 public void testShutdownNow_delayedTasks() throws InterruptedException {
671 : jsr166 1.73 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
672 : jsr166 1.54 List<ScheduledFuture> tasks = new ArrayList<>();
673 :     for (int i = 0; i < 3; i++) {
674 :     Runnable r = new NoOpRunnable();
675 :     tasks.add(p.schedule(r, 9, SECONDS));
676 :     tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
677 :     tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
678 :     }
679 : jsr166 1.55 if (testImplementationDetails)
680 :     assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
681 : jsr166 1.54 final List<Runnable> queuedTasks;
682 : dl 1.17 try {
683 : jsr166 1.54 queuedTasks = p.shutdownNow();
684 : jsr166 1.22 } catch (SecurityException ok) {
685 : jsr166 1.54 return; // Allowed in case test doesn't have privs
686 :     }
687 :     assertTrue(p.isShutdown());
688 :     assertTrue(p.getQueue().isEmpty());
689 : jsr166 1.55 if (testImplementationDetails)
690 :     assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
691 : jsr166 1.54 assertEquals(tasks.size(), queuedTasks.size());
692 :     for (ScheduledFuture task : tasks) {
693 :     assertFalse(task.isDone());
694 :     assertFalse(task.isCancelled());
695 : dl 1.17 }
696 : jsr166 1.54 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
697 :     assertTrue(p.isTerminated());
698 : dl 1.2 }
699 :    
700 : dl 1.5 /**
701 : jsr166 1.58 * By default, periodic tasks are cancelled at shutdown.
702 :     * By default, delayed tasks keep running after shutdown.
703 :     * Check that changing the default values work:
704 :     * - setExecuteExistingDelayedTasksAfterShutdownPolicy
705 :     * - setContinueExistingPeriodicTasksAfterShutdownPolicy
706 :     */
707 : jsr166 1.95 @SuppressWarnings("FutureReturnValueIgnored")
708 : jsr166 1.58 public void testShutdown_cancellation() throws Exception {
709 : jsr166 1.92 final int poolSize = 4;
710 : jsr166 1.58 final ScheduledThreadPoolExecutor p
711 :     = new ScheduledThreadPoolExecutor(poolSize);
712 : jsr166 1.89 final BlockingQueue<Runnable> q = p.getQueue();
713 : jsr166 1.88 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
714 : jsr166 1.92 final long delay = rnd.nextInt(2);
715 :     final int rounds = rnd.nextInt(1, 3);
716 : jsr166 1.88 final boolean effectiveDelayedPolicy;
717 :     final boolean effectivePeriodicPolicy;
718 :     final boolean effectiveRemovePolicy;
719 :    
720 :     if (rnd.nextBoolean())
721 :     p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
722 :     effectiveDelayedPolicy = rnd.nextBoolean());
723 :     else
724 :     effectiveDelayedPolicy = true;
725 : jsr166 1.58 assertEquals(effectiveDelayedPolicy,
726 :     p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
727 : jsr166 1.88
728 :     if (rnd.nextBoolean())
729 :     p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
730 :     effectivePeriodicPolicy = rnd.nextBoolean());
731 :     else
732 :     effectivePeriodicPolicy = false;
733 : jsr166 1.58 assertEquals(effectivePeriodicPolicy,
734 :     p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
735 : jsr166 1.88
736 :     if (rnd.nextBoolean())
737 :     p.setRemoveOnCancelPolicy(
738 :     effectiveRemovePolicy = rnd.nextBoolean());
739 :     else
740 :     effectiveRemovePolicy = false;
741 : jsr166 1.58 assertEquals(effectiveRemovePolicy,
742 :     p.getRemoveOnCancelPolicy());
743 : jsr166 1.88
744 : jsr166 1.90 final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
745 : jsr166 1.89
746 :     // Strategy: Wedge the pool with one wave of "blocker" tasks,
747 : jsr166 1.90 // then add a second wave that waits in the queue until unblocked.
748 : jsr166 1.58 final AtomicInteger ran = new AtomicInteger(0);
749 :     final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
750 :     final CountDownLatch unblock = new CountDownLatch(1);
751 : jsr166 1.90 final RuntimeException exception = new RuntimeException();
752 : jsr166 1.89
753 : jsr166 1.90 class Task implements Runnable {
754 :     public void run() {
755 :     try {
756 :     ran.getAndIncrement();
757 :     poolBlocked.countDown();
758 :     await(unblock);
759 :     } catch (Throwable fail) { threadUnexpectedException(fail); }
760 : jsr166 1.89 }
761 :     }
762 :    
763 :     class PeriodicTask extends Task {
764 :     PeriodicTask(int rounds) { this.rounds = rounds; }
765 :     int rounds;
766 : jsr166 1.90 public void run() {
767 :     if (--rounds == 0) super.run();
768 :     // throw exception to surely terminate this periodic task,
769 :     // but in a separate execution and in a detectable way.
770 :     if (rounds == -1) throw exception;
771 : jsr166 1.89 }
772 :     }
773 :    
774 :     Runnable task = new Task();
775 :    
776 :     List<Future<?>> immediates = new ArrayList<>();
777 :     List<Future<?>> delayeds = new ArrayList<>();
778 :     List<Future<?>> periodics = new ArrayList<>();
779 :    
780 :     immediates.add(p.submit(task));
781 : jsr166 1.92 delayeds.add(p.schedule(task, delay, MILLISECONDS));
782 :     periodics.add(p.scheduleAtFixedRate(
783 :     new PeriodicTask(rounds), delay, 1, MILLISECONDS));
784 :     periodics.add(p.scheduleWithFixedDelay(
785 :     new PeriodicTask(rounds), delay, 1, MILLISECONDS));
786 : jsr166 1.89
787 : jsr166 1.86 await(poolBlocked);
788 : jsr166 1.58
789 : jsr166 1.89 assertEquals(poolSize, ran.get());
790 : jsr166 1.91 assertEquals(poolSize, p.getActiveCount());
791 : jsr166 1.89 assertTrue(q.isEmpty());
792 :    
793 :     // Add second wave of tasks.
794 :     immediates.add(p.submit(task));
795 : jsr166 1.92 delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
796 :     periodics.add(p.scheduleAtFixedRate(
797 :     new PeriodicTask(rounds), delay, 1, MILLISECONDS));
798 :     periodics.add(p.scheduleWithFixedDelay(
799 :     new PeriodicTask(rounds), delay, 1, MILLISECONDS));
800 : jsr166 1.89
801 :     assertEquals(poolSize, q.size());
802 :     assertEquals(poolSize, ran.get());
803 :    
804 :     immediates.forEach(
805 :     f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
806 :    
807 :     Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
808 :     .forEach(f -> assertFalse(f.isDone()));
809 : jsr166 1.22
810 : jsr166 1.33 try { p.shutdown(); } catch (SecurityException ok) { return; }
811 : jsr166 1.58 assertTrue(p.isShutdown());
812 : jsr166 1.89 assertTrue(p.isTerminating());
813 : jsr166 1.58 assertFalse(p.isTerminated());
814 : jsr166 1.89
815 :     if (rnd.nextBoolean())
816 :     assertThrows(
817 :     RejectedExecutionException.class,
818 :     () -> p.submit(task),
819 :     () -> p.schedule(task, 1, SECONDS),
820 :     () -> p.scheduleAtFixedRate(
821 :     new PeriodicTask(1), 1, 1, SECONDS),
822 :     () -> p.scheduleWithFixedDelay(
823 :     new PeriodicTask(2), 1, 1, SECONDS));
824 :    
825 :     assertTrue(q.contains(immediates.get(1)));
826 :     assertTrue(!effectiveDelayedPolicy
827 :     ^ q.contains(delayeds.get(1)));
828 :     assertTrue(!effectivePeriodicPolicy
829 : jsr166 1.92 ^ q.containsAll(periodics.subList(2, 4)));
830 : jsr166 1.89
831 :     immediates.forEach(f -> assertFalse(f.isDone()));
832 :    
833 :     assertFalse(delayeds.get(0).isDone());
834 :     if (effectiveDelayedPolicy)
835 :     assertFalse(delayeds.get(1).isDone());
836 :     else
837 :     assertTrue(delayeds.get(1).isCancelled());
838 :    
839 : jsr166 1.91 if (effectivePeriodicPolicy)
840 :     periodics.forEach(
841 :     f -> {
842 :     assertFalse(f.isDone());
843 :     if (!periodicTasksContinue) {
844 :     assertTrue(f.cancel(false));
845 :     assertTrue(f.isCancelled());
846 :     }
847 :     });
848 :     else {
849 : jsr166 1.92 periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
850 :     periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
851 : jsr166 1.58 }
852 : jsr166 1.89
853 : jsr166 1.87 unblock.countDown(); // Release all pool threads
854 : jsr166 1.58
855 :     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
856 : jsr166 1.89 assertFalse(p.isTerminating());
857 : jsr166 1.33 assertTrue(p.isTerminated());
858 : jsr166 1.87
859 : jsr166 1.89 assertTrue(q.isEmpty());
860 :    
861 : jsr166 1.90 Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
862 :     .forEach(f -> assertTrue(f.isDone()));
863 :    
864 : jsr166 1.89 for (Future<?> f : immediates) assertNull(f.get());
865 :    
866 :     assertNull(delayeds.get(0).get());
867 :     if (effectiveDelayedPolicy)
868 :     assertNull(delayeds.get(1).get());
869 :     else
870 :     assertTrue(delayeds.get(1).isCancelled());
871 :    
872 : jsr166 1.90 if (periodicTasksContinue)
873 :     periodics.forEach(
874 :     f -> {
875 :     try { f.get(); }
876 :     catch (ExecutionException success) {
877 :     assertSame(exception, success.getCause());
878 :     }
879 :     catch (Throwable fail) { threadUnexpectedException(fail); }
880 :     });
881 :     else
882 :     periodics.forEach(f -> assertTrue(f.isCancelled()));
883 : jsr166 1.89
884 : jsr166 1.90 assertEquals(poolSize + 1
885 :     + (effectiveDelayedPolicy ? 1 : 0)
886 : jsr166 1.92 + (periodicTasksContinue ? 2 : 0),
887 : jsr166 1.90 ran.get());
888 : jsr166 1.88 }
889 : dl 1.1
890 : dl 1.10 /**
891 :     * completed submit of callable returns result
892 :     */
893 : jsr166 1.25 public void testSubmitCallable() throws Exception {
894 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
895 :     try (PoolCleaner cleaner = cleaner(e)) {
896 : dl 1.10 Future<String> future = e.submit(new StringTask());
897 :     String result = future.get();
898 :     assertSame(TEST_STRING, result);
899 :     }
900 :     }
901 :    
902 :     /**
903 :     * completed submit of runnable returns successfully
904 :     */
905 : jsr166 1.25 public void testSubmitRunnable() throws Exception {
906 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
907 :     try (PoolCleaner cleaner = cleaner(e)) {
908 : dl 1.10 Future<?> future = e.submit(new NoOpRunnable());
909 :     future.get();
910 :     assertTrue(future.isDone());
911 :     }
912 :     }
913 :    
914 :     /**
915 :     * completed submit of (runnable, result) returns result
916 :     */
917 : jsr166 1.25 public void testSubmitRunnable2() throws Exception {
918 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
919 :     try (PoolCleaner cleaner = cleaner(e)) {
920 : dl 1.10 Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
921 :     String result = future.get();
922 :     assertSame(TEST_STRING, result);
923 :     }
924 :     }
925 :    
926 :     /**
927 : jsr166 1.94 * invokeAny(null) throws NullPointerException
928 : dl 1.10 */
929 : jsr166 1.25 public void testInvokeAny1() throws Exception {
930 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
931 :     try (PoolCleaner cleaner = cleaner(e)) {
932 :     try {
933 :     e.invokeAny(null);
934 :     shouldThrow();
935 :     } catch (NullPointerException success) {}
936 : dl 1.10 }
937 :     }
938 :    
939 :     /**
940 : jsr166 1.94 * invokeAny(empty collection) throws IllegalArgumentException
941 : dl 1.10 */
942 : jsr166 1.25 public void testInvokeAny2() throws Exception {
943 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
944 :     try (PoolCleaner cleaner = cleaner(e)) {
945 :     try {
946 :     e.invokeAny(new ArrayList<Callable<String>>());
947 :     shouldThrow();
948 :     } catch (IllegalArgumentException success) {}
949 : dl 1.10 }
950 :     }
951 :    
952 :     /**
953 : jsr166 1.94 * invokeAny(c) throws NullPointerException if c has null elements
954 : dl 1.10 */
955 : jsr166 1.25 public void testInvokeAny3() throws Exception {
956 : jsr166 1.29 CountDownLatch latch = new CountDownLatch(1);
957 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
958 :     try (PoolCleaner cleaner = cleaner(e)) {
959 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
960 : jsr166 1.62 l.add(latchAwaitingStringTask(latch));
961 :     l.add(null);
962 :     try {
963 :     e.invokeAny(l);
964 :     shouldThrow();
965 :     } catch (NullPointerException success) {}
966 : jsr166 1.25 latch.countDown();
967 : dl 1.10 }
968 :     }
969 :    
970 :     /**
971 :     * invokeAny(c) throws ExecutionException if no task completes
972 :     */
973 : jsr166 1.25 public void testInvokeAny4() throws Exception {
974 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
975 :     try (PoolCleaner cleaner = cleaner(e)) {
976 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
977 : jsr166 1.62 l.add(new NPETask());
978 :     try {
979 :     e.invokeAny(l);
980 :     shouldThrow();
981 :     } catch (ExecutionException success) {
982 :     assertTrue(success.getCause() instanceof NullPointerException);
983 :     }
984 : dl 1.10 }
985 :     }
986 :    
987 :     /**
988 :     * invokeAny(c) returns result of some task
989 :     */
990 : jsr166 1.25 public void testInvokeAny5() throws Exception {
991 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
992 :     try (PoolCleaner cleaner = cleaner(e)) {
993 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
994 : dl 1.10 l.add(new StringTask());
995 :     l.add(new StringTask());
996 :     String result = e.invokeAny(l);
997 :     assertSame(TEST_STRING, result);
998 :     }
999 :     }
1000 :    
1001 :     /**
1002 :     * invokeAll(null) throws NPE
1003 :     */
1004 : jsr166 1.25 public void testInvokeAll1() throws Exception {
1005 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1006 :     try (PoolCleaner cleaner = cleaner(e)) {
1007 :     try {
1008 :     e.invokeAll(null);
1009 :     shouldThrow();
1010 :     } catch (NullPointerException success) {}
1011 : dl 1.10 }
1012 :     }
1013 :    
1014 :     /**
1015 : jsr166 1.94 * invokeAll(empty collection) returns empty list
1016 : dl 1.10 */
1017 : jsr166 1.25 public void testInvokeAll2() throws Exception {
1018 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1019 : jsr166 1.94 final Collection<Callable<String>> emptyCollection
1020 :     = Collections.emptyList();
1021 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(e)) {
1022 : jsr166 1.94 List<Future<String>> r = e.invokeAll(emptyCollection);
1023 : dl 1.10 assertTrue(r.isEmpty());
1024 :     }
1025 :     }
1026 :    
1027 :     /**
1028 :     * invokeAll(c) throws NPE if c has null elements
1029 :     */
1030 : jsr166 1.25 public void testInvokeAll3() throws Exception {
1031 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1032 :     try (PoolCleaner cleaner = cleaner(e)) {
1033 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1034 : jsr166 1.62 l.add(new StringTask());
1035 :     l.add(null);
1036 :     try {
1037 :     e.invokeAll(l);
1038 :     shouldThrow();
1039 :     } catch (NullPointerException success) {}
1040 : dl 1.10 }
1041 :     }
1042 :    
1043 :     /**
1044 :     * get of invokeAll(c) throws exception on failed task
1045 :     */
1046 : jsr166 1.25 public void testInvokeAll4() throws Exception {
1047 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1048 :     try (PoolCleaner cleaner = cleaner(e)) {
1049 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1050 : jsr166 1.62 l.add(new NPETask());
1051 :     List<Future<String>> futures = e.invokeAll(l);
1052 :     assertEquals(1, futures.size());
1053 :     try {
1054 :     futures.get(0).get();
1055 :     shouldThrow();
1056 :     } catch (ExecutionException success) {
1057 :     assertTrue(success.getCause() instanceof NullPointerException);
1058 :     }
1059 : dl 1.10 }
1060 :     }
1061 :    
1062 :     /**
1063 :     * invokeAll(c) returns results of all completed tasks
1064 :     */
1065 : jsr166 1.25 public void testInvokeAll5() throws Exception {
1066 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1067 :     try (PoolCleaner cleaner = cleaner(e)) {
1068 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1069 : dl 1.10 l.add(new StringTask());
1070 :     l.add(new StringTask());
1071 : jsr166 1.29 List<Future<String>> futures = e.invokeAll(l);
1072 :     assertEquals(2, futures.size());
1073 :     for (Future<String> future : futures)
1074 : jsr166 1.25 assertSame(TEST_STRING, future.get());
1075 : dl 1.10 }
1076 :     }
1077 :    
1078 : dl 1.11 /**
1079 :     * timed invokeAny(null) throws NPE
1080 :     */
1081 : jsr166 1.25 public void testTimedInvokeAny1() throws Exception {
1082 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1083 :     try (PoolCleaner cleaner = cleaner(e)) {
1084 :     try {
1085 : jsr166 1.94 e.invokeAny(null, randomTimeout(), randomTimeUnit());
1086 : jsr166 1.62 shouldThrow();
1087 :     } catch (NullPointerException success) {}
1088 : dl 1.11 }
1089 :     }
1090 :    
1091 :     /**
1092 : jsr166 1.94 * timed invokeAny(,,null) throws NullPointerException
1093 : dl 1.11 */
1094 : jsr166 1.25 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1095 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1096 :     try (PoolCleaner cleaner = cleaner(e)) {
1097 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1098 : jsr166 1.62 l.add(new StringTask());
1099 :     try {
1100 : jsr166 1.94 e.invokeAny(l, randomTimeout(), null);
1101 : jsr166 1.62 shouldThrow();
1102 :     } catch (NullPointerException success) {}
1103 : dl 1.11 }
1104 :     }
1105 :    
1106 :     /**
1107 : jsr166 1.94 * timed invokeAny(empty collection) throws IllegalArgumentException
1108 : dl 1.11 */
1109 : jsr166 1.25 public void testTimedInvokeAny2() throws Exception {
1110 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1111 : jsr166 1.94 final Collection<Callable<String>> emptyCollection
1112 :     = Collections.emptyList();
1113 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(e)) {
1114 :     try {
1115 : jsr166 1.94 e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1116 : jsr166 1.62 shouldThrow();
1117 :     } catch (IllegalArgumentException success) {}
1118 : dl 1.11 }
1119 :     }
1120 :    
1121 :     /**
1122 :     * timed invokeAny(c) throws NPE if c has null elements
1123 :     */
1124 : jsr166 1.25 public void testTimedInvokeAny3() throws Exception {
1125 : jsr166 1.29 CountDownLatch latch = new CountDownLatch(1);
1126 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1127 :     try (PoolCleaner cleaner = cleaner(e)) {
1128 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1129 : jsr166 1.62 l.add(latchAwaitingStringTask(latch));
1130 :     l.add(null);
1131 :     try {
1132 : jsr166 1.94 e.invokeAny(l, randomTimeout(), randomTimeUnit());
1133 : jsr166 1.62 shouldThrow();
1134 :     } catch (NullPointerException success) {}
1135 : jsr166 1.25 latch.countDown();
1136 : dl 1.11 }
1137 :     }
1138 :    
1139 :     /**
1140 :     * timed invokeAny(c) throws ExecutionException if no task completes
1141 :     */
1142 : jsr166 1.25 public void testTimedInvokeAny4() throws Exception {
1143 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1144 :     try (PoolCleaner cleaner = cleaner(e)) {
1145 : jsr166 1.75 long startTime = System.nanoTime();
1146 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1147 : jsr166 1.62 l.add(new NPETask());
1148 :     try {
1149 : jsr166 1.75 e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1150 : jsr166 1.62 shouldThrow();
1151 :     } catch (ExecutionException success) {
1152 :     assertTrue(success.getCause() instanceof NullPointerException);
1153 :     }
1154 : jsr166 1.75 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1155 : dl 1.11 }
1156 :     }
1157 :    
1158 :     /**
1159 :     * timed invokeAny(c) returns result of some task
1160 :     */
1161 : jsr166 1.25 public void testTimedInvokeAny5() throws Exception {
1162 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163 :     try (PoolCleaner cleaner = cleaner(e)) {
1164 : jsr166 1.76 long startTime = System.nanoTime();
1165 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1166 : dl 1.11 l.add(new StringTask());
1167 :     l.add(new StringTask());
1168 : jsr166 1.76 String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1169 : dl 1.11 assertSame(TEST_STRING, result);
1170 : jsr166 1.76 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1171 : dl 1.11 }
1172 :     }
1173 :    
1174 :     /**
1175 :     * timed invokeAll(null) throws NPE
1176 :     */
1177 : jsr166 1.25 public void testTimedInvokeAll1() throws Exception {
1178 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1179 :     try (PoolCleaner cleaner = cleaner(e)) {
1180 :     try {
1181 : jsr166 1.94 e.invokeAll(null, randomTimeout(), randomTimeUnit());
1182 : jsr166 1.62 shouldThrow();
1183 :     } catch (NullPointerException success) {}
1184 : dl 1.11 }
1185 :     }
1186 :    
1187 :     /**
1188 :     * timed invokeAll(,,null) throws NPE
1189 :     */
1190 : jsr166 1.25 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1191 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1192 :     try (PoolCleaner cleaner = cleaner(e)) {
1193 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1194 : jsr166 1.62 l.add(new StringTask());
1195 :     try {
1196 : jsr166 1.94 e.invokeAll(l, randomTimeout(), null);
1197 : jsr166 1.62 shouldThrow();
1198 :     } catch (NullPointerException success) {}
1199 : dl 1.11 }
1200 :     }
1201 :    
1202 :     /**
1203 : jsr166 1.94 * timed invokeAll(empty collection) returns empty list
1204 : dl 1.11 */
1205 : jsr166 1.25 public void testTimedInvokeAll2() throws Exception {
1206 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1207 : jsr166 1.94 final Collection<Callable<String>> emptyCollection
1208 :     = Collections.emptyList();
1209 : jsr166 1.62 try (PoolCleaner cleaner = cleaner(e)) {
1210 : jsr166 1.94 List<Future<String>> r =
1211 :     e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1212 : dl 1.11 assertTrue(r.isEmpty());
1213 :     }
1214 :     }
1215 :    
1216 :     /**
1217 :     * timed invokeAll(c) throws NPE if c has null elements
1218 :     */
1219 : jsr166 1.25 public void testTimedInvokeAll3() throws Exception {
1220 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1221 :     try (PoolCleaner cleaner = cleaner(e)) {
1222 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1223 : jsr166 1.62 l.add(new StringTask());
1224 :     l.add(null);
1225 :     try {
1226 : jsr166 1.94 e.invokeAll(l, randomTimeout(), randomTimeUnit());
1227 : jsr166 1.62 shouldThrow();
1228 :     } catch (NullPointerException success) {}
1229 : dl 1.11 }
1230 :     }
1231 :    
1232 :     /**
1233 :     * get of element of invokeAll(c) throws exception on failed task
1234 :     */
1235 : jsr166 1.25 public void testTimedInvokeAll4() throws Exception {
1236 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1237 :     try (PoolCleaner cleaner = cleaner(e)) {
1238 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1239 : jsr166 1.62 l.add(new NPETask());
1240 :     List<Future<String>> futures =
1241 : jsr166 1.69 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1242 : jsr166 1.62 assertEquals(1, futures.size());
1243 :     try {
1244 :     futures.get(0).get();
1245 :     shouldThrow();
1246 :     } catch (ExecutionException success) {
1247 :     assertTrue(success.getCause() instanceof NullPointerException);
1248 :     }
1249 : dl 1.11 }
1250 :     }
1251 :    
1252 :     /**
1253 :     * timed invokeAll(c) returns results of all completed tasks
1254 :     */
1255 : jsr166 1.25 public void testTimedInvokeAll5() throws Exception {
1256 : jsr166 1.62 final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1257 :     try (PoolCleaner cleaner = cleaner(e)) {
1258 : jsr166 1.83 List<Callable<String>> l = new ArrayList<>();
1259 : dl 1.11 l.add(new StringTask());
1260 :     l.add(new StringTask());
1261 : jsr166 1.29 List<Future<String>> futures =
1262 : jsr166 1.59 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1263 : jsr166 1.29 assertEquals(2, futures.size());
1264 :     for (Future<String> future : futures)
1265 : jsr166 1.25 assertSame(TEST_STRING, future.get());
1266 : dl 1.11 }
1267 :     }
1268 :    
1269 :     /**
1270 :     * timed invokeAll(c) cancels tasks not completed by timeout
1271 :     */
1272 : jsr166 1.25 public void testTimedInvokeAll6() throws Exception {
1273 : jsr166 1.74 for (long timeout = timeoutMillis();;) {
1274 :     final CountDownLatch done = new CountDownLatch(1);
1275 :     final Callable<String> waiter = new CheckedCallable<String>() {
1276 :     public String realCall() {
1277 :     try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1278 :     catch (InterruptedException ok) {}
1279 :     return "1"; }};
1280 :     final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1281 :     try (PoolCleaner cleaner = cleaner(p, done)) {
1282 : jsr166 1.52 List<Callable<String>> tasks = new ArrayList<>();
1283 :     tasks.add(new StringTask("0"));
1284 : jsr166 1.74 tasks.add(waiter);
1285 : jsr166 1.52 tasks.add(new StringTask("2"));
1286 :     long startTime = System.nanoTime();
1287 :     List<Future<String>> futures =
1288 : jsr166 1.74 p.invokeAll(tasks, timeout, MILLISECONDS);
1289 : jsr166 1.52 assertEquals(tasks.size(), futures.size());
1290 :     assertTrue(millisElapsedSince(startTime) >= timeout);
1291 :     for (Future future : futures)
1292 :     assertTrue(future.isDone());
1293 :     assertTrue(futures.get(1).isCancelled());
1294 :     try {
1295 :     assertEquals("0", futures.get(0).get());
1296 :     assertEquals("2", futures.get(2).get());
1297 :     break;
1298 :     } catch (CancellationException retryWithLongerTimeout) {
1299 :     timeout *= 2;
1300 :     if (timeout >= LONG_DELAY_MS / 2)
1301 :     fail("expected exactly one task to be cancelled");
1302 :     }
1303 :     }
1304 : dl 1.11 }
1305 :     }
1306 :    
1307 : jsr166 1.77 /**
1308 :     * A fixed delay task with overflowing period should not prevent a
1309 :     * one-shot task from executing.
1310 :     * https://bugs.openjdk.java.net/browse/JDK-8051859
1311 :     */
1312 : jsr166 1.95 @SuppressWarnings("FutureReturnValueIgnored")
1313 : jsr166 1.77 public void testScheduleWithFixedDelay_overflow() throws Exception {
1314 :     final CountDownLatch delayedDone = new CountDownLatch(1);
1315 :     final CountDownLatch immediateDone = new CountDownLatch(1);
1316 :     final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1317 :     try (PoolCleaner cleaner = cleaner(p)) {
1318 : jsr166 1.95 final Runnable delayed = () -> {
1319 : jsr166 1.77 delayedDone.countDown();
1320 : jsr166 1.95 p.submit(() -> immediateDone.countDown());
1321 :     };
1322 : jsr166 1.77 p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1323 :     await(delayedDone);
1324 :     await(immediateDone);
1325 :     }
1326 :     }
1327 :    
1328 : dl 1.1 }

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8