ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
Revision: 1.86
Committed: Sun Oct 4 02:34:48 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.85: +3 -5 lines
Log Message:
improve testGetQueue

File Contents

# Content
1 /*
2 * 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 * http://creativecommons.org/publicdomain/zero/1.0/
5 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 * Pat Fisher, Mike Judd.
7 */
8
9 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 import static java.util.concurrent.TimeUnit.SECONDS;
12
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.concurrent.ArrayBlockingQueue;
16 import java.util.concurrent.BlockingQueue;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.CancellationException;
19 import java.util.concurrent.CountDownLatch;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.FutureTask;
25 import java.util.concurrent.LinkedBlockingQueue;
26 import java.util.concurrent.RejectedExecutionException;
27 import java.util.concurrent.RejectedExecutionHandler;
28 import java.util.concurrent.SynchronousQueue;
29 import java.util.concurrent.ThreadFactory;
30 import java.util.concurrent.ThreadPoolExecutor;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicInteger;
33
34 import junit.framework.Test;
35 import junit.framework.TestSuite;
36
37 public class ThreadPoolExecutorTest extends JSR166TestCase {
38 public static void main(String[] args) {
39 main(suite(), args);
40 }
41 public static Test suite() {
42 return new TestSuite(ThreadPoolExecutorTest.class);
43 }
44
45 static class ExtendedTPE extends ThreadPoolExecutor {
46 final CountDownLatch beforeCalled = new CountDownLatch(1);
47 final CountDownLatch afterCalled = new CountDownLatch(1);
48 final CountDownLatch terminatedCalled = new CountDownLatch(1);
49
50 public ExtendedTPE() {
51 super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
52 }
53 protected void beforeExecute(Thread t, Runnable r) {
54 beforeCalled.countDown();
55 }
56 protected void afterExecute(Runnable r, Throwable t) {
57 afterCalled.countDown();
58 }
59 protected void terminated() {
60 terminatedCalled.countDown();
61 }
62
63 public boolean beforeCalled() {
64 return beforeCalled.getCount() == 0;
65 }
66 public boolean afterCalled() {
67 return afterCalled.getCount() == 0;
68 }
69 public boolean terminatedCalled() {
70 return terminatedCalled.getCount() == 0;
71 }
72 }
73
74 static class FailingThreadFactory implements ThreadFactory {
75 int calls = 0;
76 public Thread newThread(Runnable r) {
77 if (++calls > 1) return null;
78 return new Thread(r);
79 }
80 }
81
82 /**
83 * execute successfully executes a runnable
84 */
85 public void testExecute() throws InterruptedException {
86 final ThreadPoolExecutor p =
87 new ThreadPoolExecutor(1, 1,
88 LONG_DELAY_MS, MILLISECONDS,
89 new ArrayBlockingQueue<Runnable>(10));
90 try (PoolCleaner cleaner = cleaner(p)) {
91 final CountDownLatch done = new CountDownLatch(1);
92 final Runnable task = new CheckedRunnable() {
93 public void realRun() { done.countDown(); }};
94 p.execute(task);
95 assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
96 }
97 }
98
99 /**
100 * getActiveCount increases but doesn't overestimate, when a
101 * thread becomes active
102 */
103 public void testGetActiveCount() throws InterruptedException {
104 final ThreadPoolExecutor p =
105 new ThreadPoolExecutor(2, 2,
106 LONG_DELAY_MS, MILLISECONDS,
107 new ArrayBlockingQueue<Runnable>(10));
108 try (PoolCleaner cleaner = cleaner(p)) {
109 final CountDownLatch threadStarted = new CountDownLatch(1);
110 final CountDownLatch done = new CountDownLatch(1);
111 assertEquals(0, p.getActiveCount());
112 p.execute(new CheckedRunnable() {
113 public void realRun() throws InterruptedException {
114 threadStarted.countDown();
115 assertEquals(1, p.getActiveCount());
116 done.await();
117 }});
118 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
119 assertEquals(1, p.getActiveCount());
120 done.countDown();
121 }
122 }
123
124 /**
125 * prestartCoreThread starts a thread if under corePoolSize, else doesn't
126 */
127 public void testPrestartCoreThread() {
128 final ThreadPoolExecutor p =
129 new ThreadPoolExecutor(2, 6,
130 LONG_DELAY_MS, MILLISECONDS,
131 new ArrayBlockingQueue<Runnable>(10));
132 try (PoolCleaner cleaner = cleaner(p)) {
133 assertEquals(0, p.getPoolSize());
134 assertTrue(p.prestartCoreThread());
135 assertEquals(1, p.getPoolSize());
136 assertTrue(p.prestartCoreThread());
137 assertEquals(2, p.getPoolSize());
138 assertFalse(p.prestartCoreThread());
139 assertEquals(2, p.getPoolSize());
140 p.setCorePoolSize(4);
141 assertTrue(p.prestartCoreThread());
142 assertEquals(3, p.getPoolSize());
143 assertTrue(p.prestartCoreThread());
144 assertEquals(4, p.getPoolSize());
145 assertFalse(p.prestartCoreThread());
146 assertEquals(4, p.getPoolSize());
147 }
148 }
149
150 /**
151 * prestartAllCoreThreads starts all corePoolSize threads
152 */
153 public void testPrestartAllCoreThreads() {
154 final ThreadPoolExecutor p =
155 new ThreadPoolExecutor(2, 6,
156 LONG_DELAY_MS, MILLISECONDS,
157 new ArrayBlockingQueue<Runnable>(10));
158 try (PoolCleaner cleaner = cleaner(p)) {
159 assertEquals(0, p.getPoolSize());
160 p.prestartAllCoreThreads();
161 assertEquals(2, p.getPoolSize());
162 p.prestartAllCoreThreads();
163 assertEquals(2, p.getPoolSize());
164 p.setCorePoolSize(4);
165 p.prestartAllCoreThreads();
166 assertEquals(4, p.getPoolSize());
167 p.prestartAllCoreThreads();
168 assertEquals(4, p.getPoolSize());
169 }
170 }
171
172 /**
173 * getCompletedTaskCount increases, but doesn't overestimate,
174 * when tasks complete
175 */
176 public void testGetCompletedTaskCount() throws InterruptedException {
177 final ThreadPoolExecutor p =
178 new ThreadPoolExecutor(2, 2,
179 LONG_DELAY_MS, MILLISECONDS,
180 new ArrayBlockingQueue<Runnable>(10));
181 try (PoolCleaner cleaner = cleaner(p)) {
182 final CountDownLatch threadStarted = new CountDownLatch(1);
183 final CountDownLatch threadProceed = new CountDownLatch(1);
184 final CountDownLatch threadDone = new CountDownLatch(1);
185 assertEquals(0, p.getCompletedTaskCount());
186 p.execute(new CheckedRunnable() {
187 public void realRun() throws InterruptedException {
188 threadStarted.countDown();
189 assertEquals(0, p.getCompletedTaskCount());
190 threadProceed.await();
191 threadDone.countDown();
192 }});
193 await(threadStarted);
194 assertEquals(0, p.getCompletedTaskCount());
195 threadProceed.countDown();
196 threadDone.await();
197 long startTime = System.nanoTime();
198 while (p.getCompletedTaskCount() != 1) {
199 if (millisElapsedSince(startTime) > LONG_DELAY_MS)
200 fail("timed out");
201 Thread.yield();
202 }
203 }
204 }
205
206 /**
207 * getCorePoolSize returns size given in constructor if not otherwise set
208 */
209 public void testGetCorePoolSize() {
210 final ThreadPoolExecutor p =
211 new ThreadPoolExecutor(1, 1,
212 LONG_DELAY_MS, MILLISECONDS,
213 new ArrayBlockingQueue<Runnable>(10));
214 try (PoolCleaner cleaner = cleaner(p)) {
215 assertEquals(1, p.getCorePoolSize());
216 }
217 }
218
219 /**
220 * getKeepAliveTime returns value given in constructor if not otherwise set
221 */
222 public void testGetKeepAliveTime() {
223 final ThreadPoolExecutor p =
224 new ThreadPoolExecutor(2, 2,
225 1000, MILLISECONDS,
226 new ArrayBlockingQueue<Runnable>(10));
227 try (PoolCleaner cleaner = cleaner(p)) {
228 assertEquals(1, p.getKeepAliveTime(SECONDS));
229 }
230 }
231
232 /**
233 * getThreadFactory returns factory in constructor if not set
234 */
235 public void testGetThreadFactory() {
236 ThreadFactory threadFactory = new SimpleThreadFactory();
237 final ThreadPoolExecutor p =
238 new ThreadPoolExecutor(1, 2,
239 LONG_DELAY_MS, MILLISECONDS,
240 new ArrayBlockingQueue<Runnable>(10),
241 threadFactory,
242 new NoOpREHandler());
243 try (PoolCleaner cleaner = cleaner(p)) {
244 assertSame(threadFactory, p.getThreadFactory());
245 }
246 }
247
248 /**
249 * setThreadFactory sets the thread factory returned by getThreadFactory
250 */
251 public void testSetThreadFactory() {
252 final ThreadPoolExecutor p =
253 new ThreadPoolExecutor(1, 2,
254 LONG_DELAY_MS, MILLISECONDS,
255 new ArrayBlockingQueue<Runnable>(10));
256 try (PoolCleaner cleaner = cleaner(p)) {
257 ThreadFactory threadFactory = new SimpleThreadFactory();
258 p.setThreadFactory(threadFactory);
259 assertSame(threadFactory, p.getThreadFactory());
260 }
261 }
262
263 /**
264 * setThreadFactory(null) throws NPE
265 */
266 public void testSetThreadFactoryNull() {
267 final ThreadPoolExecutor p =
268 new ThreadPoolExecutor(1, 2,
269 LONG_DELAY_MS, MILLISECONDS,
270 new ArrayBlockingQueue<Runnable>(10));
271 try (PoolCleaner cleaner = cleaner(p)) {
272 try {
273 p.setThreadFactory(null);
274 shouldThrow();
275 } catch (NullPointerException success) {}
276 }
277 }
278
279 /**
280 * getRejectedExecutionHandler returns handler in constructor if not set
281 */
282 public void testGetRejectedExecutionHandler() {
283 final RejectedExecutionHandler handler = new NoOpREHandler();
284 final ThreadPoolExecutor p =
285 new ThreadPoolExecutor(1, 2,
286 LONG_DELAY_MS, MILLISECONDS,
287 new ArrayBlockingQueue<Runnable>(10),
288 handler);
289 try (PoolCleaner cleaner = cleaner(p)) {
290 assertSame(handler, p.getRejectedExecutionHandler());
291 }
292 }
293
294 /**
295 * setRejectedExecutionHandler sets the handler returned by
296 * getRejectedExecutionHandler
297 */
298 public void testSetRejectedExecutionHandler() {
299 final ThreadPoolExecutor p =
300 new ThreadPoolExecutor(1, 2,
301 LONG_DELAY_MS, MILLISECONDS,
302 new ArrayBlockingQueue<Runnable>(10));
303 try (PoolCleaner cleaner = cleaner(p)) {
304 RejectedExecutionHandler handler = new NoOpREHandler();
305 p.setRejectedExecutionHandler(handler);
306 assertSame(handler, p.getRejectedExecutionHandler());
307 }
308 }
309
310 /**
311 * setRejectedExecutionHandler(null) throws NPE
312 */
313 public void testSetRejectedExecutionHandlerNull() {
314 final ThreadPoolExecutor p =
315 new ThreadPoolExecutor(1, 2,
316 LONG_DELAY_MS, MILLISECONDS,
317 new ArrayBlockingQueue<Runnable>(10));
318 try (PoolCleaner cleaner = cleaner(p)) {
319 try {
320 p.setRejectedExecutionHandler(null);
321 shouldThrow();
322 } catch (NullPointerException success) {}
323 }
324 }
325
326 /**
327 * getLargestPoolSize increases, but doesn't overestimate, when
328 * multiple threads active
329 */
330 public void testGetLargestPoolSize() throws InterruptedException {
331 final int THREADS = 3;
332 final ThreadPoolExecutor p =
333 new ThreadPoolExecutor(THREADS, THREADS,
334 LONG_DELAY_MS, MILLISECONDS,
335 new ArrayBlockingQueue<Runnable>(10));
336 try (PoolCleaner cleaner = cleaner(p)) {
337 final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
338 final CountDownLatch done = new CountDownLatch(1);
339 assertEquals(0, p.getLargestPoolSize());
340 for (int i = 0; i < THREADS; i++)
341 p.execute(new CheckedRunnable() {
342 public void realRun() throws InterruptedException {
343 threadsStarted.countDown();
344 done.await();
345 assertEquals(THREADS, p.getLargestPoolSize());
346 }});
347 assertTrue(threadsStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
348 assertEquals(THREADS, p.getLargestPoolSize());
349 done.countDown(); // release pool
350 }
351 assertEquals(THREADS, p.getLargestPoolSize());
352 }
353
354 /**
355 * getMaximumPoolSize returns value given in constructor if not
356 * otherwise set
357 */
358 public void testGetMaximumPoolSize() {
359 final ThreadPoolExecutor p =
360 new ThreadPoolExecutor(2, 3,
361 LONG_DELAY_MS, MILLISECONDS,
362 new ArrayBlockingQueue<Runnable>(10));
363 try (PoolCleaner cleaner = cleaner(p)) {
364 assertEquals(3, p.getMaximumPoolSize());
365 p.setMaximumPoolSize(5);
366 assertEquals(5, p.getMaximumPoolSize());
367 p.setMaximumPoolSize(4);
368 assertEquals(4, p.getMaximumPoolSize());
369 }
370 }
371
372 /**
373 * getPoolSize increases, but doesn't overestimate, when threads
374 * become active
375 */
376 public void testGetPoolSize() throws InterruptedException {
377 final ThreadPoolExecutor p =
378 new ThreadPoolExecutor(1, 1,
379 LONG_DELAY_MS, MILLISECONDS,
380 new ArrayBlockingQueue<Runnable>(10));
381 try (PoolCleaner cleaner = cleaner(p)) {
382 final CountDownLatch threadStarted = new CountDownLatch(1);
383 final CountDownLatch done = new CountDownLatch(1);
384 assertEquals(0, p.getPoolSize());
385 p.execute(new CheckedRunnable() {
386 public void realRun() throws InterruptedException {
387 threadStarted.countDown();
388 assertEquals(1, p.getPoolSize());
389 done.await();
390 }});
391 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
392 assertEquals(1, p.getPoolSize());
393 done.countDown(); // release pool
394 }
395 }
396
397 /**
398 * getTaskCount increases, but doesn't overestimate, when tasks submitted
399 */
400 public void testGetTaskCount() throws InterruptedException {
401 final ThreadPoolExecutor p =
402 new ThreadPoolExecutor(1, 1,
403 LONG_DELAY_MS, MILLISECONDS,
404 new ArrayBlockingQueue<Runnable>(10));
405 try (PoolCleaner cleaner = cleaner(p)) {
406 final CountDownLatch threadStarted = new CountDownLatch(1);
407 final CountDownLatch done = new CountDownLatch(1);
408 assertEquals(0, p.getTaskCount());
409 p.execute(new CheckedRunnable() {
410 public void realRun() throws InterruptedException {
411 threadStarted.countDown();
412 assertEquals(1, p.getTaskCount());
413 done.await();
414 }});
415 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
416 assertEquals(1, p.getTaskCount());
417 done.countDown();
418 }
419 }
420
421 /**
422 * isShutdown is false before shutdown, true after
423 */
424 public void testIsShutdown() {
425 final ThreadPoolExecutor p =
426 new ThreadPoolExecutor(1, 1,
427 LONG_DELAY_MS, MILLISECONDS,
428 new ArrayBlockingQueue<Runnable>(10));
429 try (PoolCleaner cleaner = cleaner(p)) {
430 assertFalse(p.isShutdown());
431 try { p.shutdown(); } catch (SecurityException ok) { return; }
432 assertTrue(p.isShutdown());
433 }
434 }
435
436 /**
437 * awaitTermination on a non-shutdown pool times out
438 */
439 public void testAwaitTermination_timesOut() throws InterruptedException {
440 final ThreadPoolExecutor p =
441 new ThreadPoolExecutor(1, 1,
442 LONG_DELAY_MS, MILLISECONDS,
443 new ArrayBlockingQueue<Runnable>(10));
444 try (PoolCleaner cleaner = cleaner(p)) {
445 assertFalse(p.isTerminated());
446 assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
447 assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
448 assertFalse(p.awaitTermination(-1L, NANOSECONDS));
449 assertFalse(p.awaitTermination(-1L, MILLISECONDS));
450 assertFalse(p.awaitTermination(0L, NANOSECONDS));
451 assertFalse(p.awaitTermination(0L, MILLISECONDS));
452 long timeoutNanos = 999999L;
453 long startTime = System.nanoTime();
454 assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
455 assertTrue(System.nanoTime() - startTime >= timeoutNanos);
456 assertFalse(p.isTerminated());
457 startTime = System.nanoTime();
458 long timeoutMillis = timeoutMillis();
459 assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
460 assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
461 assertFalse(p.isTerminated());
462 try { p.shutdown(); } catch (SecurityException ok) { return; }
463 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
464 assertTrue(p.isTerminated());
465 }
466 }
467
468 /**
469 * isTerminated is false before termination, true after
470 */
471 public void testIsTerminated() throws InterruptedException {
472 final ThreadPoolExecutor p =
473 new ThreadPoolExecutor(1, 1,
474 LONG_DELAY_MS, MILLISECONDS,
475 new ArrayBlockingQueue<Runnable>(10));
476 try (PoolCleaner cleaner = cleaner(p)) {
477 final CountDownLatch threadStarted = new CountDownLatch(1);
478 final CountDownLatch done = new CountDownLatch(1);
479 assertFalse(p.isTerminating());
480 p.execute(new CheckedRunnable() {
481 public void realRun() throws InterruptedException {
482 assertFalse(p.isTerminating());
483 threadStarted.countDown();
484 done.await();
485 }});
486 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
487 assertFalse(p.isTerminating());
488 done.countDown();
489 try { p.shutdown(); } catch (SecurityException ok) { return; }
490 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
491 assertTrue(p.isTerminated());
492 assertFalse(p.isTerminating());
493 }
494 }
495
496 /**
497 * isTerminating is not true when running or when terminated
498 */
499 public void testIsTerminating() throws InterruptedException {
500 final ThreadPoolExecutor p =
501 new ThreadPoolExecutor(1, 1,
502 LONG_DELAY_MS, MILLISECONDS,
503 new ArrayBlockingQueue<Runnable>(10));
504 try (PoolCleaner cleaner = cleaner(p)) {
505 final CountDownLatch threadStarted = new CountDownLatch(1);
506 final CountDownLatch done = new CountDownLatch(1);
507 assertFalse(p.isTerminating());
508 p.execute(new CheckedRunnable() {
509 public void realRun() throws InterruptedException {
510 assertFalse(p.isTerminating());
511 threadStarted.countDown();
512 done.await();
513 }});
514 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
515 assertFalse(p.isTerminating());
516 done.countDown();
517 try { p.shutdown(); } catch (SecurityException ok) { return; }
518 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
519 assertTrue(p.isTerminated());
520 assertFalse(p.isTerminating());
521 }
522 }
523
524 /**
525 * getQueue returns the work queue, which contains queued tasks
526 */
527 public void testGetQueue() throws InterruptedException {
528 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
529 final ThreadPoolExecutor p =
530 new ThreadPoolExecutor(1, 1,
531 LONG_DELAY_MS, MILLISECONDS,
532 q);
533 try (PoolCleaner cleaner = cleaner(p)) {
534 final CountDownLatch threadStarted = new CountDownLatch(1);
535 final CountDownLatch done = new CountDownLatch(1);
536 FutureTask[] tasks = new FutureTask[5];
537 for (int i = 0; i < tasks.length; i++) {
538 Callable task = new CheckedCallable<Boolean>() {
539 public Boolean realCall() throws InterruptedException {
540 threadStarted.countDown();
541 assertSame(q, p.getQueue());
542 done.await();
543 return Boolean.TRUE;
544 }};
545 tasks[i] = new FutureTask(task);
546 p.execute(tasks[i]);
547 }
548 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
549 assertSame(q, p.getQueue());
550 assertFalse(q.contains(tasks[0]));
551 assertTrue(q.contains(tasks[tasks.length - 1]));
552 assertEquals(tasks.length - 1, q.size());
553 done.countDown();
554 }
555 }
556
557 /**
558 * remove(task) removes queued task, and fails to remove active task
559 */
560 public void testRemove() throws InterruptedException {
561 BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
562 final ThreadPoolExecutor p =
563 new ThreadPoolExecutor(1, 1,
564 LONG_DELAY_MS, MILLISECONDS,
565 q);
566 Runnable[] tasks = new Runnable[5];
567 final CountDownLatch threadStarted = new CountDownLatch(1);
568 final CountDownLatch done = new CountDownLatch(1);
569 try {
570 for (int i = 0; i < tasks.length; i++) {
571 tasks[i] = new CheckedRunnable() {
572 public void realRun() throws InterruptedException {
573 threadStarted.countDown();
574 done.await();
575 }};
576 p.execute(tasks[i]);
577 }
578 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
579 assertFalse(p.remove(tasks[0]));
580 assertTrue(q.contains(tasks[4]));
581 assertTrue(q.contains(tasks[3]));
582 assertTrue(p.remove(tasks[4]));
583 assertFalse(p.remove(tasks[4]));
584 assertFalse(q.contains(tasks[4]));
585 assertTrue(q.contains(tasks[3]));
586 assertTrue(p.remove(tasks[3]));
587 assertFalse(q.contains(tasks[3]));
588 } finally {
589 done.countDown();
590 joinPool(p);
591 }
592 }
593
594 /**
595 * purge removes cancelled tasks from the queue
596 */
597 public void testPurge() throws InterruptedException {
598 final CountDownLatch threadStarted = new CountDownLatch(1);
599 final CountDownLatch done = new CountDownLatch(1);
600 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
601 final ThreadPoolExecutor p =
602 new ThreadPoolExecutor(1, 1,
603 LONG_DELAY_MS, MILLISECONDS,
604 q);
605 FutureTask[] tasks = new FutureTask[5];
606 try {
607 for (int i = 0; i < tasks.length; i++) {
608 Callable task = new CheckedCallable<Boolean>() {
609 public Boolean realCall() throws InterruptedException {
610 threadStarted.countDown();
611 done.await();
612 return Boolean.TRUE;
613 }};
614 tasks[i] = new FutureTask(task);
615 p.execute(tasks[i]);
616 }
617 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
618 assertEquals(tasks.length, p.getTaskCount());
619 assertEquals(tasks.length - 1, q.size());
620 assertEquals(1L, p.getActiveCount());
621 assertEquals(0L, p.getCompletedTaskCount());
622 tasks[4].cancel(true);
623 tasks[3].cancel(false);
624 p.purge();
625 assertEquals(tasks.length - 3, q.size());
626 assertEquals(tasks.length - 2, p.getTaskCount());
627 p.purge(); // Nothing to do
628 assertEquals(tasks.length - 3, q.size());
629 assertEquals(tasks.length - 2, p.getTaskCount());
630 } finally {
631 done.countDown();
632 joinPool(p);
633 }
634 }
635
636 /**
637 * shutdownNow returns a list containing tasks that were not run,
638 * and those tasks are drained from the queue
639 */
640 public void testShutdownNow() throws InterruptedException {
641 final int poolSize = 2;
642 final int count = 5;
643 final AtomicInteger ran = new AtomicInteger(0);
644 final ThreadPoolExecutor p =
645 new ThreadPoolExecutor(poolSize, poolSize,
646 LONG_DELAY_MS, MILLISECONDS,
647 new ArrayBlockingQueue<Runnable>(10));
648 CountDownLatch threadsStarted = new CountDownLatch(poolSize);
649 Runnable waiter = new CheckedRunnable() { public void realRun() {
650 threadsStarted.countDown();
651 try {
652 MILLISECONDS.sleep(2 * LONG_DELAY_MS);
653 } catch (InterruptedException success) {}
654 ran.getAndIncrement();
655 }};
656 for (int i = 0; i < count; i++)
657 p.execute(waiter);
658 assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
659 assertEquals(poolSize, p.getActiveCount());
660 assertEquals(0, p.getCompletedTaskCount());
661 final List<Runnable> queuedTasks;
662 try {
663 queuedTasks = p.shutdownNow();
664 } catch (SecurityException ok) {
665 return; // Allowed in case test doesn't have privs
666 }
667 assertTrue(p.isShutdown());
668 assertTrue(p.getQueue().isEmpty());
669 assertEquals(count - poolSize, queuedTasks.size());
670 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
671 assertTrue(p.isTerminated());
672 assertEquals(poolSize, ran.get());
673 assertEquals(poolSize, p.getCompletedTaskCount());
674 }
675
676 // Exception Tests
677
678 /**
679 * Constructor throws if corePoolSize argument is less than zero
680 */
681 public void testConstructor1() {
682 try {
683 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
684 new ArrayBlockingQueue<Runnable>(10));
685 shouldThrow();
686 } catch (IllegalArgumentException success) {}
687 }
688
689 /**
690 * Constructor throws if maximumPoolSize is less than zero
691 */
692 public void testConstructor2() {
693 try {
694 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
695 new ArrayBlockingQueue<Runnable>(10));
696 shouldThrow();
697 } catch (IllegalArgumentException success) {}
698 }
699
700 /**
701 * Constructor throws if maximumPoolSize is equal to zero
702 */
703 public void testConstructor3() {
704 try {
705 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
706 new ArrayBlockingQueue<Runnable>(10));
707 shouldThrow();
708 } catch (IllegalArgumentException success) {}
709 }
710
711 /**
712 * Constructor throws if keepAliveTime is less than zero
713 */
714 public void testConstructor4() {
715 try {
716 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
717 new ArrayBlockingQueue<Runnable>(10));
718 shouldThrow();
719 } catch (IllegalArgumentException success) {}
720 }
721
722 /**
723 * Constructor throws if corePoolSize is greater than the maximumPoolSize
724 */
725 public void testConstructor5() {
726 try {
727 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
728 new ArrayBlockingQueue<Runnable>(10));
729 shouldThrow();
730 } catch (IllegalArgumentException success) {}
731 }
732
733 /**
734 * Constructor throws if workQueue is set to null
735 */
736 public void testConstructorNullPointerException() {
737 try {
738 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
739 (BlockingQueue) null);
740 shouldThrow();
741 } catch (NullPointerException success) {}
742 }
743
744 /**
745 * Constructor throws if corePoolSize argument is less than zero
746 */
747 public void testConstructor6() {
748 try {
749 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
750 new ArrayBlockingQueue<Runnable>(10),
751 new SimpleThreadFactory());
752 shouldThrow();
753 } catch (IllegalArgumentException success) {}
754 }
755
756 /**
757 * Constructor throws if maximumPoolSize is less than zero
758 */
759 public void testConstructor7() {
760 try {
761 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
762 new ArrayBlockingQueue<Runnable>(10),
763 new SimpleThreadFactory());
764 shouldThrow();
765 } catch (IllegalArgumentException success) {}
766 }
767
768 /**
769 * Constructor throws if maximumPoolSize is equal to zero
770 */
771 public void testConstructor8() {
772 try {
773 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
774 new ArrayBlockingQueue<Runnable>(10),
775 new SimpleThreadFactory());
776 shouldThrow();
777 } catch (IllegalArgumentException success) {}
778 }
779
780 /**
781 * Constructor throws if keepAliveTime is less than zero
782 */
783 public void testConstructor9() {
784 try {
785 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
786 new ArrayBlockingQueue<Runnable>(10),
787 new SimpleThreadFactory());
788 shouldThrow();
789 } catch (IllegalArgumentException success) {}
790 }
791
792 /**
793 * Constructor throws if corePoolSize is greater than the maximumPoolSize
794 */
795 public void testConstructor10() {
796 try {
797 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
798 new ArrayBlockingQueue<Runnable>(10),
799 new SimpleThreadFactory());
800 shouldThrow();
801 } catch (IllegalArgumentException success) {}
802 }
803
804 /**
805 * Constructor throws if workQueue is set to null
806 */
807 public void testConstructorNullPointerException2() {
808 try {
809 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
810 (BlockingQueue) null,
811 new SimpleThreadFactory());
812 shouldThrow();
813 } catch (NullPointerException success) {}
814 }
815
816 /**
817 * Constructor throws if threadFactory is set to null
818 */
819 public void testConstructorNullPointerException3() {
820 try {
821 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
822 new ArrayBlockingQueue<Runnable>(10),
823 (ThreadFactory) null);
824 shouldThrow();
825 } catch (NullPointerException success) {}
826 }
827
828 /**
829 * Constructor throws if corePoolSize argument is less than zero
830 */
831 public void testConstructor11() {
832 try {
833 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
834 new ArrayBlockingQueue<Runnable>(10),
835 new NoOpREHandler());
836 shouldThrow();
837 } catch (IllegalArgumentException success) {}
838 }
839
840 /**
841 * Constructor throws if maximumPoolSize is less than zero
842 */
843 public void testConstructor12() {
844 try {
845 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
846 new ArrayBlockingQueue<Runnable>(10),
847 new NoOpREHandler());
848 shouldThrow();
849 } catch (IllegalArgumentException success) {}
850 }
851
852 /**
853 * Constructor throws if maximumPoolSize is equal to zero
854 */
855 public void testConstructor13() {
856 try {
857 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
858 new ArrayBlockingQueue<Runnable>(10),
859 new NoOpREHandler());
860 shouldThrow();
861 } catch (IllegalArgumentException success) {}
862 }
863
864 /**
865 * Constructor throws if keepAliveTime is less than zero
866 */
867 public void testConstructor14() {
868 try {
869 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
870 new ArrayBlockingQueue<Runnable>(10),
871 new NoOpREHandler());
872 shouldThrow();
873 } catch (IllegalArgumentException success) {}
874 }
875
876 /**
877 * Constructor throws if corePoolSize is greater than the maximumPoolSize
878 */
879 public void testConstructor15() {
880 try {
881 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
882 new ArrayBlockingQueue<Runnable>(10),
883 new NoOpREHandler());
884 shouldThrow();
885 } catch (IllegalArgumentException success) {}
886 }
887
888 /**
889 * Constructor throws if workQueue is set to null
890 */
891 public void testConstructorNullPointerException4() {
892 try {
893 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
894 (BlockingQueue) null,
895 new NoOpREHandler());
896 shouldThrow();
897 } catch (NullPointerException success) {}
898 }
899
900 /**
901 * Constructor throws if handler is set to null
902 */
903 public void testConstructorNullPointerException5() {
904 try {
905 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
906 new ArrayBlockingQueue<Runnable>(10),
907 (RejectedExecutionHandler) null);
908 shouldThrow();
909 } catch (NullPointerException success) {}
910 }
911
912 /**
913 * Constructor throws if corePoolSize argument is less than zero
914 */
915 public void testConstructor16() {
916 try {
917 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
918 new ArrayBlockingQueue<Runnable>(10),
919 new SimpleThreadFactory(),
920 new NoOpREHandler());
921 shouldThrow();
922 } catch (IllegalArgumentException success) {}
923 }
924
925 /**
926 * Constructor throws if maximumPoolSize is less than zero
927 */
928 public void testConstructor17() {
929 try {
930 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
931 new ArrayBlockingQueue<Runnable>(10),
932 new SimpleThreadFactory(),
933 new NoOpREHandler());
934 shouldThrow();
935 } catch (IllegalArgumentException success) {}
936 }
937
938 /**
939 * Constructor throws if maximumPoolSize is equal to zero
940 */
941 public void testConstructor18() {
942 try {
943 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
944 new ArrayBlockingQueue<Runnable>(10),
945 new SimpleThreadFactory(),
946 new NoOpREHandler());
947 shouldThrow();
948 } catch (IllegalArgumentException success) {}
949 }
950
951 /**
952 * Constructor throws if keepAliveTime is less than zero
953 */
954 public void testConstructor19() {
955 try {
956 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
957 new ArrayBlockingQueue<Runnable>(10),
958 new SimpleThreadFactory(),
959 new NoOpREHandler());
960 shouldThrow();
961 } catch (IllegalArgumentException success) {}
962 }
963
964 /**
965 * Constructor throws if corePoolSize is greater than the maximumPoolSize
966 */
967 public void testConstructor20() {
968 try {
969 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
970 new ArrayBlockingQueue<Runnable>(10),
971 new SimpleThreadFactory(),
972 new NoOpREHandler());
973 shouldThrow();
974 } catch (IllegalArgumentException success) {}
975 }
976
977 /**
978 * Constructor throws if workQueue is null
979 */
980 public void testConstructorNullPointerException6() {
981 try {
982 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
983 (BlockingQueue) null,
984 new SimpleThreadFactory(),
985 new NoOpREHandler());
986 shouldThrow();
987 } catch (NullPointerException success) {}
988 }
989
990 /**
991 * Constructor throws if handler is null
992 */
993 public void testConstructorNullPointerException7() {
994 try {
995 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
996 new ArrayBlockingQueue<Runnable>(10),
997 new SimpleThreadFactory(),
998 (RejectedExecutionHandler) null);
999 shouldThrow();
1000 } catch (NullPointerException success) {}
1001 }
1002
1003 /**
1004 * Constructor throws if ThreadFactory is null
1005 */
1006 public void testConstructorNullPointerException8() {
1007 try {
1008 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1009 new ArrayBlockingQueue<Runnable>(10),
1010 (ThreadFactory) null,
1011 new NoOpREHandler());
1012 shouldThrow();
1013 } catch (NullPointerException success) {}
1014 }
1015
1016 /**
1017 * get of submitted callable throws InterruptedException if interrupted
1018 */
1019 public void testInterruptedSubmit() throws InterruptedException {
1020 final ThreadPoolExecutor p =
1021 new ThreadPoolExecutor(1, 1,
1022 60, SECONDS,
1023 new ArrayBlockingQueue<Runnable>(10));
1024
1025 final CountDownLatch threadStarted = new CountDownLatch(1);
1026 final CountDownLatch done = new CountDownLatch(1);
1027 try {
1028 Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1029 public void realRun() throws Exception {
1030 Callable task = new CheckedCallable<Boolean>() {
1031 public Boolean realCall() throws InterruptedException {
1032 threadStarted.countDown();
1033 done.await();
1034 return Boolean.TRUE;
1035 }};
1036 p.submit(task).get();
1037 }});
1038
1039 assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
1040 t.interrupt();
1041 awaitTermination(t, MEDIUM_DELAY_MS);
1042 } finally {
1043 done.countDown();
1044 joinPool(p);
1045 }
1046 }
1047
1048 /**
1049 * execute throws RejectedExecutionException if saturated.
1050 */
1051 public void testSaturatedExecute() {
1052 ThreadPoolExecutor p =
1053 new ThreadPoolExecutor(1, 1,
1054 LONG_DELAY_MS, MILLISECONDS,
1055 new ArrayBlockingQueue<Runnable>(1));
1056 final CountDownLatch done = new CountDownLatch(1);
1057 try {
1058 Runnable task = new CheckedRunnable() {
1059 public void realRun() throws InterruptedException {
1060 done.await();
1061 }};
1062 for (int i = 0; i < 2; ++i)
1063 p.execute(task);
1064 for (int i = 0; i < 2; ++i) {
1065 try {
1066 p.execute(task);
1067 shouldThrow();
1068 } catch (RejectedExecutionException success) {}
1069 assertTrue(p.getTaskCount() <= 2);
1070 }
1071 } finally {
1072 done.countDown();
1073 joinPool(p);
1074 }
1075 }
1076
1077 /**
1078 * submit(runnable) throws RejectedExecutionException if saturated.
1079 */
1080 public void testSaturatedSubmitRunnable() {
1081 ThreadPoolExecutor p =
1082 new ThreadPoolExecutor(1, 1,
1083 LONG_DELAY_MS, MILLISECONDS,
1084 new ArrayBlockingQueue<Runnable>(1));
1085 final CountDownLatch done = new CountDownLatch(1);
1086 try {
1087 Runnable task = new CheckedRunnable() {
1088 public void realRun() throws InterruptedException {
1089 done.await();
1090 }};
1091 for (int i = 0; i < 2; ++i)
1092 p.submit(task);
1093 for (int i = 0; i < 2; ++i) {
1094 try {
1095 p.execute(task);
1096 shouldThrow();
1097 } catch (RejectedExecutionException success) {}
1098 assertTrue(p.getTaskCount() <= 2);
1099 }
1100 } finally {
1101 done.countDown();
1102 joinPool(p);
1103 }
1104 }
1105
1106 /**
1107 * submit(callable) throws RejectedExecutionException if saturated.
1108 */
1109 public void testSaturatedSubmitCallable() {
1110 ThreadPoolExecutor p =
1111 new ThreadPoolExecutor(1, 1,
1112 LONG_DELAY_MS, MILLISECONDS,
1113 new ArrayBlockingQueue<Runnable>(1));
1114 final CountDownLatch done = new CountDownLatch(1);
1115 try {
1116 Runnable task = new CheckedRunnable() {
1117 public void realRun() throws InterruptedException {
1118 done.await();
1119 }};
1120 for (int i = 0; i < 2; ++i)
1121 p.submit(Executors.callable(task));
1122 for (int i = 0; i < 2; ++i) {
1123 try {
1124 p.execute(task);
1125 shouldThrow();
1126 } catch (RejectedExecutionException success) {}
1127 assertTrue(p.getTaskCount() <= 2);
1128 }
1129 } finally {
1130 done.countDown();
1131 joinPool(p);
1132 }
1133 }
1134
1135 /**
1136 * executor using CallerRunsPolicy runs task if saturated.
1137 */
1138 public void testSaturatedExecute2() {
1139 RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1140 final ThreadPoolExecutor p =
1141 new ThreadPoolExecutor(1, 1,
1142 LONG_DELAY_MS,
1143 MILLISECONDS,
1144 new ArrayBlockingQueue<Runnable>(1),
1145 h);
1146 try {
1147 TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1148 for (int i = 0; i < tasks.length; ++i)
1149 tasks[i] = new TrackedNoOpRunnable();
1150 TrackedLongRunnable mr = new TrackedLongRunnable();
1151 p.execute(mr);
1152 for (int i = 0; i < tasks.length; ++i)
1153 p.execute(tasks[i]);
1154 for (int i = 1; i < tasks.length; ++i)
1155 assertTrue(tasks[i].done);
1156 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1157 } finally {
1158 joinPool(p);
1159 }
1160 }
1161
1162 /**
1163 * executor using DiscardPolicy drops task if saturated.
1164 */
1165 public void testSaturatedExecute3() {
1166 RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1167 final ThreadPoolExecutor p =
1168 new ThreadPoolExecutor(1, 1,
1169 LONG_DELAY_MS, MILLISECONDS,
1170 new ArrayBlockingQueue<Runnable>(1),
1171 h);
1172 try {
1173 TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1174 for (int i = 0; i < tasks.length; ++i)
1175 tasks[i] = new TrackedNoOpRunnable();
1176 p.execute(new TrackedLongRunnable());
1177 for (TrackedNoOpRunnable task : tasks)
1178 p.execute(task);
1179 for (TrackedNoOpRunnable task : tasks)
1180 assertFalse(task.done);
1181 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1182 } finally {
1183 joinPool(p);
1184 }
1185 }
1186
1187 /**
1188 * executor using DiscardOldestPolicy drops oldest task if saturated.
1189 */
1190 public void testSaturatedExecute4() {
1191 RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1192 final ThreadPoolExecutor p =
1193 new ThreadPoolExecutor(1, 1,
1194 LONG_DELAY_MS, MILLISECONDS,
1195 new ArrayBlockingQueue<Runnable>(1),
1196 h);
1197 try {
1198 p.execute(new TrackedLongRunnable());
1199 TrackedLongRunnable r2 = new TrackedLongRunnable();
1200 p.execute(r2);
1201 assertTrue(p.getQueue().contains(r2));
1202 TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1203 p.execute(r3);
1204 assertFalse(p.getQueue().contains(r2));
1205 assertTrue(p.getQueue().contains(r3));
1206 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1207 } finally {
1208 joinPool(p);
1209 }
1210 }
1211
1212 /**
1213 * execute throws RejectedExecutionException if shutdown
1214 */
1215 public void testRejectedExecutionExceptionOnShutdown() {
1216 ThreadPoolExecutor p =
1217 new ThreadPoolExecutor(1, 1,
1218 LONG_DELAY_MS, MILLISECONDS,
1219 new ArrayBlockingQueue<Runnable>(1));
1220 try { p.shutdown(); } catch (SecurityException ok) { return; }
1221 try {
1222 p.execute(new NoOpRunnable());
1223 shouldThrow();
1224 } catch (RejectedExecutionException success) {}
1225
1226 joinPool(p);
1227 }
1228
1229 /**
1230 * execute using CallerRunsPolicy drops task on shutdown
1231 */
1232 public void testCallerRunsOnShutdown() {
1233 RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1234 final ThreadPoolExecutor p =
1235 new ThreadPoolExecutor(1, 1,
1236 LONG_DELAY_MS, MILLISECONDS,
1237 new ArrayBlockingQueue<Runnable>(1), h);
1238
1239 try { p.shutdown(); } catch (SecurityException ok) { return; }
1240 try {
1241 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1242 p.execute(r);
1243 assertFalse(r.done);
1244 } finally {
1245 joinPool(p);
1246 }
1247 }
1248
1249 /**
1250 * execute using DiscardPolicy drops task on shutdown
1251 */
1252 public void testDiscardOnShutdown() {
1253 RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1254 ThreadPoolExecutor p =
1255 new ThreadPoolExecutor(1, 1,
1256 LONG_DELAY_MS, MILLISECONDS,
1257 new ArrayBlockingQueue<Runnable>(1),
1258 h);
1259
1260 try { p.shutdown(); } catch (SecurityException ok) { return; }
1261 try {
1262 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1263 p.execute(r);
1264 assertFalse(r.done);
1265 } finally {
1266 joinPool(p);
1267 }
1268 }
1269
1270 /**
1271 * execute using DiscardOldestPolicy drops task on shutdown
1272 */
1273 public void testDiscardOldestOnShutdown() {
1274 RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1275 ThreadPoolExecutor p =
1276 new ThreadPoolExecutor(1, 1,
1277 LONG_DELAY_MS, MILLISECONDS,
1278 new ArrayBlockingQueue<Runnable>(1),
1279 h);
1280
1281 try { p.shutdown(); } catch (SecurityException ok) { return; }
1282 try {
1283 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1284 p.execute(r);
1285 assertFalse(r.done);
1286 } finally {
1287 joinPool(p);
1288 }
1289 }
1290
1291 /**
1292 * execute(null) throws NPE
1293 */
1294 public void testExecuteNull() {
1295 ThreadPoolExecutor p =
1296 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1297 new ArrayBlockingQueue<Runnable>(10));
1298 try {
1299 p.execute(null);
1300 shouldThrow();
1301 } catch (NullPointerException success) {}
1302
1303 joinPool(p);
1304 }
1305
1306 /**
1307 * setCorePoolSize of negative value throws IllegalArgumentException
1308 */
1309 public void testCorePoolSizeIllegalArgumentException() {
1310 ThreadPoolExecutor p =
1311 new ThreadPoolExecutor(1, 2,
1312 LONG_DELAY_MS, MILLISECONDS,
1313 new ArrayBlockingQueue<Runnable>(10));
1314 try {
1315 p.setCorePoolSize(-1);
1316 shouldThrow();
1317 } catch (IllegalArgumentException success) {
1318 } finally {
1319 try { p.shutdown(); } catch (SecurityException ok) { return; }
1320 }
1321 joinPool(p);
1322 }
1323
1324 /**
1325 * setMaximumPoolSize(int) throws IllegalArgumentException if
1326 * given a value less the core pool size
1327 */
1328 public void testMaximumPoolSizeIllegalArgumentException() {
1329 ThreadPoolExecutor p =
1330 new ThreadPoolExecutor(2, 3,
1331 LONG_DELAY_MS, MILLISECONDS,
1332 new ArrayBlockingQueue<Runnable>(10));
1333 try {
1334 p.setMaximumPoolSize(1);
1335 shouldThrow();
1336 } catch (IllegalArgumentException success) {
1337 } finally {
1338 try { p.shutdown(); } catch (SecurityException ok) { return; }
1339 }
1340 joinPool(p);
1341 }
1342
1343 /**
1344 * setMaximumPoolSize throws IllegalArgumentException
1345 * if given a negative value
1346 */
1347 public void testMaximumPoolSizeIllegalArgumentException2() {
1348 ThreadPoolExecutor p =
1349 new ThreadPoolExecutor(2, 3,
1350 LONG_DELAY_MS, MILLISECONDS,
1351 new ArrayBlockingQueue<Runnable>(10));
1352 try {
1353 p.setMaximumPoolSize(-1);
1354 shouldThrow();
1355 } catch (IllegalArgumentException success) {
1356 } finally {
1357 try { p.shutdown(); } catch (SecurityException ok) { return; }
1358 }
1359 joinPool(p);
1360 }
1361
1362 /**
1363 * Configuration changes that allow core pool size greater than
1364 * max pool size result in IllegalArgumentException.
1365 */
1366 public void testPoolSizeInvariants() {
1367 ThreadPoolExecutor p =
1368 new ThreadPoolExecutor(1, 1,
1369 LONG_DELAY_MS, MILLISECONDS,
1370 new ArrayBlockingQueue<Runnable>(10));
1371 for (int s = 1; s < 5; s++) {
1372 p.setMaximumPoolSize(s);
1373 p.setCorePoolSize(s);
1374 try {
1375 p.setMaximumPoolSize(s - 1);
1376 shouldThrow();
1377 } catch (IllegalArgumentException success) {}
1378 assertEquals(s, p.getCorePoolSize());
1379 assertEquals(s, p.getMaximumPoolSize());
1380 try {
1381 p.setCorePoolSize(s + 1);
1382 shouldThrow();
1383 } catch (IllegalArgumentException success) {}
1384 assertEquals(s, p.getCorePoolSize());
1385 assertEquals(s, p.getMaximumPoolSize());
1386 }
1387 joinPool(p);
1388 }
1389
1390 /**
1391 * setKeepAliveTime throws IllegalArgumentException
1392 * when given a negative value
1393 */
1394 public void testKeepAliveTimeIllegalArgumentException() {
1395 ThreadPoolExecutor p =
1396 new ThreadPoolExecutor(2, 3,
1397 LONG_DELAY_MS, MILLISECONDS,
1398 new ArrayBlockingQueue<Runnable>(10));
1399 try {
1400 p.setKeepAliveTime(-1,MILLISECONDS);
1401 shouldThrow();
1402 } catch (IllegalArgumentException success) {
1403 } finally {
1404 try { p.shutdown(); } catch (SecurityException ok) { return; }
1405 }
1406 joinPool(p);
1407 }
1408
1409 /**
1410 * terminated() is called on termination
1411 */
1412 public void testTerminated() {
1413 ExtendedTPE p = new ExtendedTPE();
1414 try { p.shutdown(); } catch (SecurityException ok) { return; }
1415 assertTrue(p.terminatedCalled());
1416 joinPool(p);
1417 }
1418
1419 /**
1420 * beforeExecute and afterExecute are called when executing task
1421 */
1422 public void testBeforeAfter() throws InterruptedException {
1423 ExtendedTPE p = new ExtendedTPE();
1424 try {
1425 final CountDownLatch done = new CountDownLatch(1);
1426 p.execute(new CheckedRunnable() {
1427 public void realRun() {
1428 done.countDown();
1429 }});
1430 await(p.afterCalled);
1431 assertEquals(0, done.getCount());
1432 assertTrue(p.afterCalled());
1433 assertTrue(p.beforeCalled());
1434 try { p.shutdown(); } catch (SecurityException ok) { return; }
1435 } finally {
1436 joinPool(p);
1437 }
1438 }
1439
1440 /**
1441 * completed submit of callable returns result
1442 */
1443 public void testSubmitCallable() throws Exception {
1444 ExecutorService e =
1445 new ThreadPoolExecutor(2, 2,
1446 LONG_DELAY_MS, MILLISECONDS,
1447 new ArrayBlockingQueue<Runnable>(10));
1448 try {
1449 Future<String> future = e.submit(new StringTask());
1450 String result = future.get();
1451 assertSame(TEST_STRING, result);
1452 } finally {
1453 joinPool(e);
1454 }
1455 }
1456
1457 /**
1458 * completed submit of runnable returns successfully
1459 */
1460 public void testSubmitRunnable() throws Exception {
1461 ExecutorService e =
1462 new ThreadPoolExecutor(2, 2,
1463 LONG_DELAY_MS, MILLISECONDS,
1464 new ArrayBlockingQueue<Runnable>(10));
1465 try {
1466 Future<?> future = e.submit(new NoOpRunnable());
1467 future.get();
1468 assertTrue(future.isDone());
1469 } finally {
1470 joinPool(e);
1471 }
1472 }
1473
1474 /**
1475 * completed submit of (runnable, result) returns result
1476 */
1477 public void testSubmitRunnable2() throws Exception {
1478 ExecutorService e =
1479 new ThreadPoolExecutor(2, 2,
1480 LONG_DELAY_MS, MILLISECONDS,
1481 new ArrayBlockingQueue<Runnable>(10));
1482 try {
1483 Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1484 String result = future.get();
1485 assertSame(TEST_STRING, result);
1486 } finally {
1487 joinPool(e);
1488 }
1489 }
1490
1491 /**
1492 * invokeAny(null) throws NPE
1493 */
1494 public void testInvokeAny1() throws Exception {
1495 ExecutorService e =
1496 new ThreadPoolExecutor(2, 2,
1497 LONG_DELAY_MS, MILLISECONDS,
1498 new ArrayBlockingQueue<Runnable>(10));
1499 try {
1500 e.invokeAny(null);
1501 shouldThrow();
1502 } catch (NullPointerException success) {
1503 } finally {
1504 joinPool(e);
1505 }
1506 }
1507
1508 /**
1509 * invokeAny(empty collection) throws IAE
1510 */
1511 public void testInvokeAny2() throws Exception {
1512 ExecutorService e =
1513 new ThreadPoolExecutor(2, 2,
1514 LONG_DELAY_MS, MILLISECONDS,
1515 new ArrayBlockingQueue<Runnable>(10));
1516 try {
1517 e.invokeAny(new ArrayList<Callable<String>>());
1518 shouldThrow();
1519 } catch (IllegalArgumentException success) {
1520 } finally {
1521 joinPool(e);
1522 }
1523 }
1524
1525 /**
1526 * invokeAny(c) throws NPE if c has null elements
1527 */
1528 public void testInvokeAny3() throws Exception {
1529 final CountDownLatch latch = new CountDownLatch(1);
1530 final ExecutorService e =
1531 new ThreadPoolExecutor(2, 2,
1532 LONG_DELAY_MS, MILLISECONDS,
1533 new ArrayBlockingQueue<Runnable>(10));
1534 List<Callable<String>> l = new ArrayList<Callable<String>>();
1535 l.add(latchAwaitingStringTask(latch));
1536 l.add(null);
1537 try {
1538 e.invokeAny(l);
1539 shouldThrow();
1540 } catch (NullPointerException success) {
1541 } finally {
1542 latch.countDown();
1543 joinPool(e);
1544 }
1545 }
1546
1547 /**
1548 * invokeAny(c) throws ExecutionException if no task completes
1549 */
1550 public void testInvokeAny4() throws Exception {
1551 ExecutorService e =
1552 new ThreadPoolExecutor(2, 2,
1553 LONG_DELAY_MS, MILLISECONDS,
1554 new ArrayBlockingQueue<Runnable>(10));
1555 List<Callable<String>> l = new ArrayList<Callable<String>>();
1556 l.add(new NPETask());
1557 try {
1558 e.invokeAny(l);
1559 shouldThrow();
1560 } catch (ExecutionException success) {
1561 assertTrue(success.getCause() instanceof NullPointerException);
1562 } finally {
1563 joinPool(e);
1564 }
1565 }
1566
1567 /**
1568 * invokeAny(c) returns result of some task
1569 */
1570 public void testInvokeAny5() throws Exception {
1571 ExecutorService e =
1572 new ThreadPoolExecutor(2, 2,
1573 LONG_DELAY_MS, MILLISECONDS,
1574 new ArrayBlockingQueue<Runnable>(10));
1575 try {
1576 List<Callable<String>> l = new ArrayList<Callable<String>>();
1577 l.add(new StringTask());
1578 l.add(new StringTask());
1579 String result = e.invokeAny(l);
1580 assertSame(TEST_STRING, result);
1581 } finally {
1582 joinPool(e);
1583 }
1584 }
1585
1586 /**
1587 * invokeAll(null) throws NPE
1588 */
1589 public void testInvokeAll1() throws Exception {
1590 ExecutorService e =
1591 new ThreadPoolExecutor(2, 2,
1592 LONG_DELAY_MS, MILLISECONDS,
1593 new ArrayBlockingQueue<Runnable>(10));
1594 try {
1595 e.invokeAll(null);
1596 shouldThrow();
1597 } catch (NullPointerException success) {
1598 } finally {
1599 joinPool(e);
1600 }
1601 }
1602
1603 /**
1604 * invokeAll(empty collection) returns empty collection
1605 */
1606 public void testInvokeAll2() throws InterruptedException {
1607 ExecutorService e =
1608 new ThreadPoolExecutor(2, 2,
1609 LONG_DELAY_MS, MILLISECONDS,
1610 new ArrayBlockingQueue<Runnable>(10));
1611 try {
1612 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1613 assertTrue(r.isEmpty());
1614 } finally {
1615 joinPool(e);
1616 }
1617 }
1618
1619 /**
1620 * invokeAll(c) throws NPE if c has null elements
1621 */
1622 public void testInvokeAll3() throws Exception {
1623 ExecutorService e =
1624 new ThreadPoolExecutor(2, 2,
1625 LONG_DELAY_MS, MILLISECONDS,
1626 new ArrayBlockingQueue<Runnable>(10));
1627 List<Callable<String>> l = new ArrayList<Callable<String>>();
1628 l.add(new StringTask());
1629 l.add(null);
1630 try {
1631 e.invokeAll(l);
1632 shouldThrow();
1633 } catch (NullPointerException success) {
1634 } finally {
1635 joinPool(e);
1636 }
1637 }
1638
1639 /**
1640 * get of element of invokeAll(c) throws exception on failed task
1641 */
1642 public void testInvokeAll4() throws Exception {
1643 ExecutorService e =
1644 new ThreadPoolExecutor(2, 2,
1645 LONG_DELAY_MS, MILLISECONDS,
1646 new ArrayBlockingQueue<Runnable>(10));
1647 try {
1648 List<Callable<String>> l = new ArrayList<Callable<String>>();
1649 l.add(new NPETask());
1650 List<Future<String>> futures = e.invokeAll(l);
1651 assertEquals(1, futures.size());
1652 try {
1653 futures.get(0).get();
1654 shouldThrow();
1655 } catch (ExecutionException success) {
1656 assertTrue(success.getCause() instanceof NullPointerException);
1657 }
1658 } finally {
1659 joinPool(e);
1660 }
1661 }
1662
1663 /**
1664 * invokeAll(c) returns results of all completed tasks
1665 */
1666 public void testInvokeAll5() throws Exception {
1667 ExecutorService e =
1668 new ThreadPoolExecutor(2, 2,
1669 LONG_DELAY_MS, MILLISECONDS,
1670 new ArrayBlockingQueue<Runnable>(10));
1671 try {
1672 List<Callable<String>> l = new ArrayList<Callable<String>>();
1673 l.add(new StringTask());
1674 l.add(new StringTask());
1675 List<Future<String>> futures = e.invokeAll(l);
1676 assertEquals(2, futures.size());
1677 for (Future<String> future : futures)
1678 assertSame(TEST_STRING, future.get());
1679 } finally {
1680 joinPool(e);
1681 }
1682 }
1683
1684 /**
1685 * timed invokeAny(null) throws NPE
1686 */
1687 public void testTimedInvokeAny1() throws Exception {
1688 ExecutorService e =
1689 new ThreadPoolExecutor(2, 2,
1690 LONG_DELAY_MS, MILLISECONDS,
1691 new ArrayBlockingQueue<Runnable>(10));
1692 try {
1693 e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1694 shouldThrow();
1695 } catch (NullPointerException success) {
1696 } finally {
1697 joinPool(e);
1698 }
1699 }
1700
1701 /**
1702 * timed invokeAny(,,null) throws NPE
1703 */
1704 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1705 ExecutorService e =
1706 new ThreadPoolExecutor(2, 2,
1707 LONG_DELAY_MS, MILLISECONDS,
1708 new ArrayBlockingQueue<Runnable>(10));
1709 List<Callable<String>> l = new ArrayList<Callable<String>>();
1710 l.add(new StringTask());
1711 try {
1712 e.invokeAny(l, MEDIUM_DELAY_MS, null);
1713 shouldThrow();
1714 } catch (NullPointerException success) {
1715 } finally {
1716 joinPool(e);
1717 }
1718 }
1719
1720 /**
1721 * timed invokeAny(empty collection) throws IAE
1722 */
1723 public void testTimedInvokeAny2() throws Exception {
1724 ExecutorService e =
1725 new ThreadPoolExecutor(2, 2,
1726 LONG_DELAY_MS, MILLISECONDS,
1727 new ArrayBlockingQueue<Runnable>(10));
1728 try {
1729 e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1730 shouldThrow();
1731 } catch (IllegalArgumentException success) {
1732 } finally {
1733 joinPool(e);
1734 }
1735 }
1736
1737 /**
1738 * timed invokeAny(c) throws NPE if c has null elements
1739 */
1740 public void testTimedInvokeAny3() throws Exception {
1741 final CountDownLatch latch = new CountDownLatch(1);
1742 final ExecutorService e =
1743 new ThreadPoolExecutor(2, 2,
1744 LONG_DELAY_MS, MILLISECONDS,
1745 new ArrayBlockingQueue<Runnable>(10));
1746 List<Callable<String>> l = new ArrayList<Callable<String>>();
1747 l.add(latchAwaitingStringTask(latch));
1748 l.add(null);
1749 try {
1750 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1751 shouldThrow();
1752 } catch (NullPointerException success) {
1753 } finally {
1754 latch.countDown();
1755 joinPool(e);
1756 }
1757 }
1758
1759 /**
1760 * timed invokeAny(c) throws ExecutionException if no task completes
1761 */
1762 public void testTimedInvokeAny4() throws Exception {
1763 ExecutorService e =
1764 new ThreadPoolExecutor(2, 2,
1765 LONG_DELAY_MS, MILLISECONDS,
1766 new ArrayBlockingQueue<Runnable>(10));
1767 List<Callable<String>> l = new ArrayList<Callable<String>>();
1768 l.add(new NPETask());
1769 try {
1770 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1771 shouldThrow();
1772 } catch (ExecutionException success) {
1773 assertTrue(success.getCause() instanceof NullPointerException);
1774 } finally {
1775 joinPool(e);
1776 }
1777 }
1778
1779 /**
1780 * timed invokeAny(c) returns result of some task
1781 */
1782 public void testTimedInvokeAny5() throws Exception {
1783 ExecutorService e =
1784 new ThreadPoolExecutor(2, 2,
1785 LONG_DELAY_MS, MILLISECONDS,
1786 new ArrayBlockingQueue<Runnable>(10));
1787 try {
1788 List<Callable<String>> l = new ArrayList<Callable<String>>();
1789 l.add(new StringTask());
1790 l.add(new StringTask());
1791 String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1792 assertSame(TEST_STRING, result);
1793 } finally {
1794 joinPool(e);
1795 }
1796 }
1797
1798 /**
1799 * timed invokeAll(null) throws NPE
1800 */
1801 public void testTimedInvokeAll1() throws Exception {
1802 ExecutorService e =
1803 new ThreadPoolExecutor(2, 2,
1804 LONG_DELAY_MS, MILLISECONDS,
1805 new ArrayBlockingQueue<Runnable>(10));
1806 try {
1807 e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1808 shouldThrow();
1809 } catch (NullPointerException success) {
1810 } finally {
1811 joinPool(e);
1812 }
1813 }
1814
1815 /**
1816 * timed invokeAll(,,null) throws NPE
1817 */
1818 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1819 ExecutorService e =
1820 new ThreadPoolExecutor(2, 2,
1821 LONG_DELAY_MS, MILLISECONDS,
1822 new ArrayBlockingQueue<Runnable>(10));
1823 List<Callable<String>> l = new ArrayList<Callable<String>>();
1824 l.add(new StringTask());
1825 try {
1826 e.invokeAll(l, MEDIUM_DELAY_MS, null);
1827 shouldThrow();
1828 } catch (NullPointerException success) {
1829 } finally {
1830 joinPool(e);
1831 }
1832 }
1833
1834 /**
1835 * timed invokeAll(empty collection) returns empty collection
1836 */
1837 public void testTimedInvokeAll2() throws InterruptedException {
1838 ExecutorService e =
1839 new ThreadPoolExecutor(2, 2,
1840 LONG_DELAY_MS, MILLISECONDS,
1841 new ArrayBlockingQueue<Runnable>(10));
1842 try {
1843 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1844 assertTrue(r.isEmpty());
1845 } finally {
1846 joinPool(e);
1847 }
1848 }
1849
1850 /**
1851 * timed invokeAll(c) throws NPE if c has null elements
1852 */
1853 public void testTimedInvokeAll3() throws Exception {
1854 ExecutorService e =
1855 new ThreadPoolExecutor(2, 2,
1856 LONG_DELAY_MS, MILLISECONDS,
1857 new ArrayBlockingQueue<Runnable>(10));
1858 List<Callable<String>> l = new ArrayList<Callable<String>>();
1859 l.add(new StringTask());
1860 l.add(null);
1861 try {
1862 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1863 shouldThrow();
1864 } catch (NullPointerException success) {
1865 } finally {
1866 joinPool(e);
1867 }
1868 }
1869
1870 /**
1871 * get of element of invokeAll(c) throws exception on failed task
1872 */
1873 public void testTimedInvokeAll4() throws Exception {
1874 ExecutorService e =
1875 new ThreadPoolExecutor(2, 2,
1876 LONG_DELAY_MS, MILLISECONDS,
1877 new ArrayBlockingQueue<Runnable>(10));
1878 List<Callable<String>> l = new ArrayList<Callable<String>>();
1879 l.add(new NPETask());
1880 List<Future<String>> futures =
1881 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1882 assertEquals(1, futures.size());
1883 try {
1884 futures.get(0).get();
1885 shouldThrow();
1886 } catch (ExecutionException success) {
1887 assertTrue(success.getCause() instanceof NullPointerException);
1888 } finally {
1889 joinPool(e);
1890 }
1891 }
1892
1893 /**
1894 * timed invokeAll(c) returns results of all completed tasks
1895 */
1896 public void testTimedInvokeAll5() throws Exception {
1897 ExecutorService e =
1898 new ThreadPoolExecutor(2, 2,
1899 LONG_DELAY_MS, MILLISECONDS,
1900 new ArrayBlockingQueue<Runnable>(10));
1901 try {
1902 List<Callable<String>> l = new ArrayList<Callable<String>>();
1903 l.add(new StringTask());
1904 l.add(new StringTask());
1905 List<Future<String>> futures =
1906 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1907 assertEquals(2, futures.size());
1908 for (Future<String> future : futures)
1909 assertSame(TEST_STRING, future.get());
1910 } finally {
1911 joinPool(e);
1912 }
1913 }
1914
1915 /**
1916 * timed invokeAll(c) cancels tasks not completed by timeout
1917 */
1918 public void testTimedInvokeAll6() throws Exception {
1919 ExecutorService e =
1920 new ThreadPoolExecutor(2, 2,
1921 LONG_DELAY_MS, MILLISECONDS,
1922 new ArrayBlockingQueue<Runnable>(10));
1923 try {
1924 for (long timeout = timeoutMillis();;) {
1925 List<Callable<String>> tasks = new ArrayList<>();
1926 tasks.add(new StringTask("0"));
1927 tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1928 tasks.add(new StringTask("2"));
1929 long startTime = System.nanoTime();
1930 List<Future<String>> futures =
1931 e.invokeAll(tasks, timeout, MILLISECONDS);
1932 assertEquals(tasks.size(), futures.size());
1933 assertTrue(millisElapsedSince(startTime) >= timeout);
1934 for (Future future : futures)
1935 assertTrue(future.isDone());
1936 assertTrue(futures.get(1).isCancelled());
1937 try {
1938 assertEquals("0", futures.get(0).get());
1939 assertEquals("2", futures.get(2).get());
1940 break;
1941 } catch (CancellationException retryWithLongerTimeout) {
1942 timeout *= 2;
1943 if (timeout >= LONG_DELAY_MS / 2)
1944 fail("expected exactly one task to be cancelled");
1945 }
1946 }
1947 } finally {
1948 joinPool(e);
1949 }
1950 }
1951
1952 /**
1953 * Execution continues if there is at least one thread even if
1954 * thread factory fails to create more
1955 */
1956 public void testFailingThreadFactory() throws InterruptedException {
1957 final ExecutorService e =
1958 new ThreadPoolExecutor(100, 100,
1959 LONG_DELAY_MS, MILLISECONDS,
1960 new LinkedBlockingQueue<Runnable>(),
1961 new FailingThreadFactory());
1962 try {
1963 final int TASKS = 100;
1964 final CountDownLatch done = new CountDownLatch(TASKS);
1965 for (int k = 0; k < TASKS; ++k)
1966 e.execute(new CheckedRunnable() {
1967 public void realRun() {
1968 done.countDown();
1969 }});
1970 assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1971 } finally {
1972 joinPool(e);
1973 }
1974 }
1975
1976 /**
1977 * allowsCoreThreadTimeOut is by default false.
1978 */
1979 public void testAllowsCoreThreadTimeOut() {
1980 final ThreadPoolExecutor p =
1981 new ThreadPoolExecutor(2, 2,
1982 1000, MILLISECONDS,
1983 new ArrayBlockingQueue<Runnable>(10));
1984 assertFalse(p.allowsCoreThreadTimeOut());
1985 joinPool(p);
1986 }
1987
1988 /**
1989 * allowCoreThreadTimeOut(true) causes idle threads to time out
1990 */
1991 public void testAllowCoreThreadTimeOut_true() throws Exception {
1992 long keepAliveTime = timeoutMillis();
1993 final ThreadPoolExecutor p =
1994 new ThreadPoolExecutor(2, 10,
1995 keepAliveTime, MILLISECONDS,
1996 new ArrayBlockingQueue<Runnable>(10));
1997 final CountDownLatch threadStarted = new CountDownLatch(1);
1998 try {
1999 p.allowCoreThreadTimeOut(true);
2000 p.execute(new CheckedRunnable() {
2001 public void realRun() {
2002 threadStarted.countDown();
2003 assertEquals(1, p.getPoolSize());
2004 }});
2005 await(threadStarted);
2006 delay(keepAliveTime);
2007 long startTime = System.nanoTime();
2008 while (p.getPoolSize() > 0
2009 && millisElapsedSince(startTime) < LONG_DELAY_MS)
2010 Thread.yield();
2011 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
2012 assertEquals(0, p.getPoolSize());
2013 } finally {
2014 joinPool(p);
2015 }
2016 }
2017
2018 /**
2019 * allowCoreThreadTimeOut(false) causes idle threads not to time out
2020 */
2021 public void testAllowCoreThreadTimeOut_false() throws Exception {
2022 long keepAliveTime = timeoutMillis();
2023 final ThreadPoolExecutor p =
2024 new ThreadPoolExecutor(2, 10,
2025 keepAliveTime, MILLISECONDS,
2026 new ArrayBlockingQueue<Runnable>(10));
2027 final CountDownLatch threadStarted = new CountDownLatch(1);
2028 try {
2029 p.allowCoreThreadTimeOut(false);
2030 p.execute(new CheckedRunnable() {
2031 public void realRun() throws InterruptedException {
2032 threadStarted.countDown();
2033 assertTrue(p.getPoolSize() >= 1);
2034 }});
2035 delay(2 * keepAliveTime);
2036 assertTrue(p.getPoolSize() >= 1);
2037 } finally {
2038 joinPool(p);
2039 }
2040 }
2041
2042 /**
2043 * execute allows the same task to be submitted multiple times, even
2044 * if rejected
2045 */
2046 public void testRejectedRecycledTask() throws InterruptedException {
2047 final int nTasks = 1000;
2048 final CountDownLatch done = new CountDownLatch(nTasks);
2049 final Runnable recycledTask = new Runnable() {
2050 public void run() {
2051 done.countDown();
2052 }};
2053 final ThreadPoolExecutor p =
2054 new ThreadPoolExecutor(1, 30,
2055 60, SECONDS,
2056 new ArrayBlockingQueue(30));
2057 try {
2058 for (int i = 0; i < nTasks; ++i) {
2059 for (;;) {
2060 try {
2061 p.execute(recycledTask);
2062 break;
2063 }
2064 catch (RejectedExecutionException ignore) {}
2065 }
2066 }
2067 // enough time to run all tasks
2068 assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2069 } finally {
2070 joinPool(p);
2071 }
2072 }
2073
2074 /**
2075 * get(cancelled task) throws CancellationException
2076 */
2077 public void testGet_cancelled() throws Exception {
2078 final ExecutorService e =
2079 new ThreadPoolExecutor(1, 1,
2080 LONG_DELAY_MS, MILLISECONDS,
2081 new LinkedBlockingQueue<Runnable>());
2082 try {
2083 final CountDownLatch blockerStarted = new CountDownLatch(1);
2084 final CountDownLatch done = new CountDownLatch(1);
2085 final List<Future<?>> futures = new ArrayList<>();
2086 for (int i = 0; i < 2; i++) {
2087 Runnable r = new CheckedRunnable() { public void realRun()
2088 throws Throwable {
2089 blockerStarted.countDown();
2090 assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
2091 }};
2092 futures.add(e.submit(r));
2093 }
2094 assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
2095 for (Future<?> future : futures) future.cancel(false);
2096 for (Future<?> future : futures) {
2097 try {
2098 future.get();
2099 shouldThrow();
2100 } catch (CancellationException success) {}
2101 try {
2102 future.get(LONG_DELAY_MS, MILLISECONDS);
2103 shouldThrow();
2104 } catch (CancellationException success) {}
2105 assertTrue(future.isCancelled());
2106 assertTrue(future.isDone());
2107 }
2108 done.countDown();
2109 } finally {
2110 joinPool(e);
2111 }
2112 }
2113
2114 }