ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ThreadPoolExecutorTest.java (file contents):
Revision 1.69 by jsr166, Sun Oct 4 01:29:09 2015 UTC vs.
Revision 1.128 by jsr166, Wed Jan 27 01:57:24 2021 UTC

# Line 11 | Line 11 | import static java.util.concurrent.TimeU
11   import static java.util.concurrent.TimeUnit.SECONDS;
12  
13   import java.util.ArrayList;
14 + import java.util.Collection;
15 + import java.util.Collections;
16   import java.util.List;
17   import java.util.concurrent.ArrayBlockingQueue;
18   import java.util.concurrent.BlockingQueue;
# Line 18 | Line 20 | import java.util.concurrent.Callable;
20   import java.util.concurrent.CancellationException;
21   import java.util.concurrent.CountDownLatch;
22   import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Executors;
23   import java.util.concurrent.ExecutorService;
24   import java.util.concurrent.Future;
25   import java.util.concurrent.FutureTask;
# Line 27 | Line 28 | import java.util.concurrent.RejectedExec
28   import java.util.concurrent.RejectedExecutionHandler;
29   import java.util.concurrent.SynchronousQueue;
30   import java.util.concurrent.ThreadFactory;
31 + import java.util.concurrent.ThreadLocalRandom;
32   import java.util.concurrent.ThreadPoolExecutor;
33 < import java.util.concurrent.TimeUnit;
33 > import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
34 > import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
35 > import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
36 > import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
37   import java.util.concurrent.atomic.AtomicInteger;
38 + import java.util.concurrent.atomic.AtomicReference;
39  
40   import junit.framework.Test;
41   import junit.framework.TestSuite;
# Line 87 | Line 93 | public class ThreadPoolExecutorTest exte
93              new ThreadPoolExecutor(1, 1,
94                                     LONG_DELAY_MS, MILLISECONDS,
95                                     new ArrayBlockingQueue<Runnable>(10));
96 <        final CountDownLatch done = new CountDownLatch(1);
97 <        final Runnable task = new CheckedRunnable() {
98 <            public void realRun() {
99 <                done.countDown();
94 <            }};
95 <        try {
96 >        try (PoolCleaner cleaner = cleaner(p)) {
97 >            final CountDownLatch done = new CountDownLatch(1);
98 >            final Runnable task = new CheckedRunnable() {
99 >                public void realRun() { done.countDown(); }};
100              p.execute(task);
101 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
98 <        } finally {
99 <            joinPool(p);
101 >            await(done);
102          }
103      }
104  
# Line 105 | Line 107 | public class ThreadPoolExecutorTest exte
107       * thread becomes active
108       */
109      public void testGetActiveCount() throws InterruptedException {
110 +        final CountDownLatch done = new CountDownLatch(1);
111          final ThreadPoolExecutor p =
112              new ThreadPoolExecutor(2, 2,
113                                     LONG_DELAY_MS, MILLISECONDS,
114                                     new ArrayBlockingQueue<Runnable>(10));
115 <        final CountDownLatch threadStarted = new CountDownLatch(1);
116 <        final CountDownLatch done = new CountDownLatch(1);
114 <        try {
115 >        try (PoolCleaner cleaner = cleaner(p, done)) {
116 >            final CountDownLatch threadStarted = new CountDownLatch(1);
117              assertEquals(0, p.getActiveCount());
118              p.execute(new CheckedRunnable() {
119                  public void realRun() throws InterruptedException {
120                      threadStarted.countDown();
121                      assertEquals(1, p.getActiveCount());
122 <                    done.await();
122 >                    await(done);
123                  }});
124 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
124 >            await(threadStarted);
125              assertEquals(1, p.getActiveCount());
124        } finally {
125            done.countDown();
126            joinPool(p);
126          }
127      }
128  
# Line 193 | Line 192 | public class ThreadPoolExecutorTest exte
192                  public void realRun() throws InterruptedException {
193                      threadStarted.countDown();
194                      assertEquals(0, p.getCompletedTaskCount());
195 <                    threadProceed.await();
195 >                    await(threadProceed);
196                      threadDone.countDown();
197                  }});
198              await(threadStarted);
199              assertEquals(0, p.getCompletedTaskCount());
200              threadProceed.countDown();
201 <            threadDone.await();
201 >            await(threadDone);
202              long startTime = System.nanoTime();
203              while (p.getCompletedTaskCount() != 1) {
204                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 230 | Line 229 | public class ThreadPoolExecutorTest exte
229              new ThreadPoolExecutor(2, 2,
230                                     1000, MILLISECONDS,
231                                     new ArrayBlockingQueue<Runnable>(10));
232 <        assertEquals(1, p.getKeepAliveTime(SECONDS));
233 <        joinPool(p);
232 >        try (PoolCleaner cleaner = cleaner(p)) {
233 >            assertEquals(1, p.getKeepAliveTime(SECONDS));
234 >        }
235      }
236  
237      /**
238       * getThreadFactory returns factory in constructor if not set
239       */
240      public void testGetThreadFactory() {
241 <        ThreadFactory tf = new SimpleThreadFactory();
241 >        ThreadFactory threadFactory = new SimpleThreadFactory();
242          final ThreadPoolExecutor p =
243              new ThreadPoolExecutor(1, 2,
244                                     LONG_DELAY_MS, MILLISECONDS,
245                                     new ArrayBlockingQueue<Runnable>(10),
246 <                                   tf,
246 >                                   threadFactory,
247                                     new NoOpREHandler());
248 <        assertSame(tf, p.getThreadFactory());
249 <        joinPool(p);
248 >        try (PoolCleaner cleaner = cleaner(p)) {
249 >            assertSame(threadFactory, p.getThreadFactory());
250 >        }
251      }
252  
253      /**
# Line 257 | Line 258 | public class ThreadPoolExecutorTest exte
258              new ThreadPoolExecutor(1, 2,
259                                     LONG_DELAY_MS, MILLISECONDS,
260                                     new ArrayBlockingQueue<Runnable>(10));
261 <        ThreadFactory tf = new SimpleThreadFactory();
262 <        p.setThreadFactory(tf);
263 <        assertSame(tf, p.getThreadFactory());
264 <        joinPool(p);
261 >        try (PoolCleaner cleaner = cleaner(p)) {
262 >            ThreadFactory threadFactory = new SimpleThreadFactory();
263 >            p.setThreadFactory(threadFactory);
264 >            assertSame(threadFactory, p.getThreadFactory());
265 >        }
266      }
267  
268      /**
# Line 271 | Line 273 | public class ThreadPoolExecutorTest exte
273              new ThreadPoolExecutor(1, 2,
274                                     LONG_DELAY_MS, MILLISECONDS,
275                                     new ArrayBlockingQueue<Runnable>(10));
276 <        try {
277 <            p.setThreadFactory(null);
278 <            shouldThrow();
279 <        } catch (NullPointerException success) {
280 <        } finally {
281 <            joinPool(p);
276 >        try (PoolCleaner cleaner = cleaner(p)) {
277 >            try {
278 >                p.setThreadFactory(null);
279 >                shouldThrow();
280 >            } catch (NullPointerException success) {}
281 >        }
282 >    }
283 >
284 >    /**
285 >     * The default rejected execution handler is AbortPolicy.
286 >     */
287 >    public void testDefaultRejectedExecutionHandler() {
288 >        final ThreadPoolExecutor p =
289 >            new ThreadPoolExecutor(1, 2,
290 >                                   LONG_DELAY_MS, MILLISECONDS,
291 >                                   new ArrayBlockingQueue<Runnable>(10));
292 >        try (PoolCleaner cleaner = cleaner(p)) {
293 >            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
294          }
295      }
296  
# Line 284 | Line 298 | public class ThreadPoolExecutorTest exte
298       * getRejectedExecutionHandler returns handler in constructor if not set
299       */
300      public void testGetRejectedExecutionHandler() {
301 <        final RejectedExecutionHandler h = new NoOpREHandler();
301 >        final RejectedExecutionHandler handler = new NoOpREHandler();
302          final ThreadPoolExecutor p =
303              new ThreadPoolExecutor(1, 2,
304                                     LONG_DELAY_MS, MILLISECONDS,
305                                     new ArrayBlockingQueue<Runnable>(10),
306 <                                   h);
307 <        assertSame(h, p.getRejectedExecutionHandler());
308 <        joinPool(p);
306 >                                   handler);
307 >        try (PoolCleaner cleaner = cleaner(p)) {
308 >            assertSame(handler, p.getRejectedExecutionHandler());
309 >        }
310      }
311  
312      /**
# Line 303 | Line 318 | public class ThreadPoolExecutorTest exte
318              new ThreadPoolExecutor(1, 2,
319                                     LONG_DELAY_MS, MILLISECONDS,
320                                     new ArrayBlockingQueue<Runnable>(10));
321 <        RejectedExecutionHandler h = new NoOpREHandler();
322 <        p.setRejectedExecutionHandler(h);
323 <        assertSame(h, p.getRejectedExecutionHandler());
324 <        joinPool(p);
321 >        try (PoolCleaner cleaner = cleaner(p)) {
322 >            RejectedExecutionHandler handler = new NoOpREHandler();
323 >            p.setRejectedExecutionHandler(handler);
324 >            assertSame(handler, p.getRejectedExecutionHandler());
325 >        }
326      }
327  
328      /**
# Line 317 | Line 333 | public class ThreadPoolExecutorTest exte
333              new ThreadPoolExecutor(1, 2,
334                                     LONG_DELAY_MS, MILLISECONDS,
335                                     new ArrayBlockingQueue<Runnable>(10));
336 <        try {
337 <            p.setRejectedExecutionHandler(null);
338 <            shouldThrow();
339 <        } catch (NullPointerException success) {
340 <        } finally {
325 <            joinPool(p);
336 >        try (PoolCleaner cleaner = cleaner(p)) {
337 >            try {
338 >                p.setRejectedExecutionHandler(null);
339 >                shouldThrow();
340 >            } catch (NullPointerException success) {}
341          }
342      }
343  
# Line 332 | Line 347 | public class ThreadPoolExecutorTest exte
347       */
348      public void testGetLargestPoolSize() throws InterruptedException {
349          final int THREADS = 3;
350 +        final CountDownLatch done = new CountDownLatch(1);
351          final ThreadPoolExecutor p =
352              new ThreadPoolExecutor(THREADS, THREADS,
353                                     LONG_DELAY_MS, MILLISECONDS,
354                                     new ArrayBlockingQueue<Runnable>(10));
355 <        final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
340 <        final CountDownLatch done = new CountDownLatch(1);
341 <        try {
355 >        try (PoolCleaner cleaner = cleaner(p, done)) {
356              assertEquals(0, p.getLargestPoolSize());
357 +            final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
358              for (int i = 0; i < THREADS; i++)
359                  p.execute(new CheckedRunnable() {
360                      public void realRun() throws InterruptedException {
361                          threadsStarted.countDown();
362 <                        done.await();
362 >                        await(done);
363                          assertEquals(THREADS, p.getLargestPoolSize());
364                      }});
365 <            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
351 <            assertEquals(THREADS, p.getLargestPoolSize());
352 <        } finally {
353 <            done.countDown();
354 <            joinPool(p);
365 >            await(threadsStarted);
366              assertEquals(THREADS, p.getLargestPoolSize());
367          }
368 +        assertEquals(THREADS, p.getLargestPoolSize());
369      }
370  
371      /**
# Line 365 | Line 377 | public class ThreadPoolExecutorTest exte
377              new ThreadPoolExecutor(2, 3,
378                                     LONG_DELAY_MS, MILLISECONDS,
379                                     new ArrayBlockingQueue<Runnable>(10));
380 <        assertEquals(3, p.getMaximumPoolSize());
381 <        joinPool(p);
380 >        try (PoolCleaner cleaner = cleaner(p)) {
381 >            assertEquals(3, p.getMaximumPoolSize());
382 >            p.setMaximumPoolSize(5);
383 >            assertEquals(5, p.getMaximumPoolSize());
384 >            p.setMaximumPoolSize(4);
385 >            assertEquals(4, p.getMaximumPoolSize());
386 >        }
387      }
388  
389      /**
# Line 374 | Line 391 | public class ThreadPoolExecutorTest exte
391       * become active
392       */
393      public void testGetPoolSize() throws InterruptedException {
394 +        final CountDownLatch done = new CountDownLatch(1);
395          final ThreadPoolExecutor p =
396              new ThreadPoolExecutor(1, 1,
397                                     LONG_DELAY_MS, MILLISECONDS,
398                                     new ArrayBlockingQueue<Runnable>(10));
399 <        final CountDownLatch threadStarted = new CountDownLatch(1);
382 <        final CountDownLatch done = new CountDownLatch(1);
383 <        try {
399 >        try (PoolCleaner cleaner = cleaner(p, done)) {
400              assertEquals(0, p.getPoolSize());
401 +            final CountDownLatch threadStarted = new CountDownLatch(1);
402              p.execute(new CheckedRunnable() {
403                  public void realRun() throws InterruptedException {
404                      threadStarted.countDown();
405                      assertEquals(1, p.getPoolSize());
406 <                    done.await();
406 >                    await(done);
407                  }});
408 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
408 >            await(threadStarted);
409              assertEquals(1, p.getPoolSize());
393        } finally {
394            done.countDown();
395            joinPool(p);
410          }
411      }
412  
# Line 400 | Line 414 | public class ThreadPoolExecutorTest exte
414       * getTaskCount increases, but doesn't overestimate, when tasks submitted
415       */
416      public void testGetTaskCount() throws InterruptedException {
417 +        final int TASKS = 3;
418 +        final CountDownLatch done = new CountDownLatch(1);
419          final ThreadPoolExecutor p =
420              new ThreadPoolExecutor(1, 1,
421                                     LONG_DELAY_MS, MILLISECONDS,
422                                     new ArrayBlockingQueue<Runnable>(10));
423 <        final CountDownLatch threadStarted = new CountDownLatch(1);
424 <        final CountDownLatch done = new CountDownLatch(1);
409 <        try {
423 >        try (PoolCleaner cleaner = cleaner(p, done)) {
424 >            final CountDownLatch threadStarted = new CountDownLatch(1);
425              assertEquals(0, p.getTaskCount());
426 +            assertEquals(0, p.getCompletedTaskCount());
427              p.execute(new CheckedRunnable() {
428                  public void realRun() throws InterruptedException {
429                      threadStarted.countDown();
430 <                    assertEquals(1, p.getTaskCount());
415 <                    done.await();
430 >                    await(done);
431                  }});
432 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
432 >            await(threadStarted);
433              assertEquals(1, p.getTaskCount());
434 <        } finally {
435 <            done.countDown();
436 <            joinPool(p);
434 >            assertEquals(0, p.getCompletedTaskCount());
435 >            for (int i = 0; i < TASKS; i++) {
436 >                assertEquals(1 + i, p.getTaskCount());
437 >                p.execute(new CheckedRunnable() {
438 >                    public void realRun() throws InterruptedException {
439 >                        threadStarted.countDown();
440 >                        assertEquals(1 + TASKS, p.getTaskCount());
441 >                        await(done);
442 >                    }});
443 >            }
444 >            assertEquals(1 + TASKS, p.getTaskCount());
445 >            assertEquals(0, p.getCompletedTaskCount());
446          }
447 +        assertEquals(1 + TASKS, p.getTaskCount());
448 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
449      }
450  
451      /**
# Line 430 | Line 456 | public class ThreadPoolExecutorTest exte
456              new ThreadPoolExecutor(1, 1,
457                                     LONG_DELAY_MS, MILLISECONDS,
458                                     new ArrayBlockingQueue<Runnable>(10));
459 <        assertFalse(p.isShutdown());
460 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
461 <        assertTrue(p.isShutdown());
462 <        joinPool(p);
459 >        try (PoolCleaner cleaner = cleaner(p)) {
460 >            assertFalse(p.isShutdown());
461 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
462 >            assertTrue(p.isShutdown());
463 >        }
464      }
465  
466      /**
# Line 444 | Line 471 | public class ThreadPoolExecutorTest exte
471              new ThreadPoolExecutor(1, 1,
472                                     LONG_DELAY_MS, MILLISECONDS,
473                                     new ArrayBlockingQueue<Runnable>(10));
474 <        assertFalse(p.isTerminated());
475 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
476 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
477 <        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
478 <        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
479 <        assertFalse(p.awaitTermination(0L, NANOSECONDS));
480 <        assertFalse(p.awaitTermination(0L, MILLISECONDS));
481 <        long timeoutNanos = 999999L;
482 <        long startTime = System.nanoTime();
483 <        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
484 <        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
485 <        assertFalse(p.isTerminated());
486 <        startTime = System.nanoTime();
487 <        long timeoutMillis = timeoutMillis();
488 <        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
489 <        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
490 <        assertFalse(p.isTerminated());
491 <        p.shutdown();
492 <        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
493 <        assertTrue(p.isTerminated());
474 >        try (PoolCleaner cleaner = cleaner(p)) {
475 >            assertFalse(p.isTerminated());
476 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
477 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
478 >            assertFalse(p.awaitTermination(-1L, NANOSECONDS));
479 >            assertFalse(p.awaitTermination(-1L, MILLISECONDS));
480 >            assertFalse(p.awaitTermination(randomExpiredTimeout(),
481 >                                           randomTimeUnit()));
482 >            long timeoutNanos = 999999L;
483 >            long startTime = System.nanoTime();
484 >            assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
485 >            assertTrue(System.nanoTime() - startTime >= timeoutNanos);
486 >            assertFalse(p.isTerminated());
487 >            startTime = System.nanoTime();
488 >            long timeoutMillis = timeoutMillis();
489 >            assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
490 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
491 >            assertFalse(p.isTerminated());
492 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
493 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494 >            assertTrue(p.isTerminated());
495 >        }
496      }
497  
498      /**
# Line 474 | Line 503 | public class ThreadPoolExecutorTest exte
503              new ThreadPoolExecutor(1, 1,
504                                     LONG_DELAY_MS, MILLISECONDS,
505                                     new ArrayBlockingQueue<Runnable>(10));
506 <        final CountDownLatch threadStarted = new CountDownLatch(1);
507 <        final CountDownLatch done = new CountDownLatch(1);
508 <        assertFalse(p.isTerminated());
509 <        try {
506 >        try (PoolCleaner cleaner = cleaner(p)) {
507 >            final CountDownLatch threadStarted = new CountDownLatch(1);
508 >            final CountDownLatch done = new CountDownLatch(1);
509 >            assertFalse(p.isTerminating());
510              p.execute(new CheckedRunnable() {
511                  public void realRun() throws InterruptedException {
512 <                    assertFalse(p.isTerminated());
512 >                    assertFalse(p.isTerminating());
513                      threadStarted.countDown();
514 <                    done.await();
514 >                    await(done);
515                  }});
516 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
516 >            await(threadStarted);
517              assertFalse(p.isTerminating());
518              done.countDown();
490        } finally {
519              try { p.shutdown(); } catch (SecurityException ok) { return; }
520 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
521 +            assertTrue(p.isTerminated());
522 +            assertFalse(p.isTerminating());
523          }
493        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494        assertTrue(p.isTerminated());
524      }
525  
526      /**
# Line 502 | Line 531 | public class ThreadPoolExecutorTest exte
531              new ThreadPoolExecutor(1, 1,
532                                     LONG_DELAY_MS, MILLISECONDS,
533                                     new ArrayBlockingQueue<Runnable>(10));
534 <        final CountDownLatch threadStarted = new CountDownLatch(1);
535 <        final CountDownLatch done = new CountDownLatch(1);
536 <        try {
534 >        try (PoolCleaner cleaner = cleaner(p)) {
535 >            final CountDownLatch threadStarted = new CountDownLatch(1);
536 >            final CountDownLatch done = new CountDownLatch(1);
537              assertFalse(p.isTerminating());
538              p.execute(new CheckedRunnable() {
539                  public void realRun() throws InterruptedException {
540                      assertFalse(p.isTerminating());
541                      threadStarted.countDown();
542 <                    done.await();
542 >                    await(done);
543                  }});
544 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
544 >            await(threadStarted);
545              assertFalse(p.isTerminating());
546              done.countDown();
518        } finally {
547              try { p.shutdown(); } catch (SecurityException ok) { return; }
548 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
549 +            assertTrue(p.isTerminated());
550 +            assertFalse(p.isTerminating());
551          }
521        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
522        assertTrue(p.isTerminated());
523        assertFalse(p.isTerminating());
552      }
553  
554      /**
555       * getQueue returns the work queue, which contains queued tasks
556       */
557      public void testGetQueue() throws InterruptedException {
558 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
558 >        final CountDownLatch done = new CountDownLatch(1);
559 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
560          final ThreadPoolExecutor p =
561              new ThreadPoolExecutor(1, 1,
562                                     LONG_DELAY_MS, MILLISECONDS,
563                                     q);
564 <        final CountDownLatch threadStarted = new CountDownLatch(1);
565 <        final CountDownLatch done = new CountDownLatch(1);
566 <        try {
567 <            FutureTask[] tasks = new FutureTask[5];
564 >        try (PoolCleaner cleaner = cleaner(p, done)) {
565 >            final CountDownLatch threadStarted = new CountDownLatch(1);
566 >            FutureTask[] rtasks = new FutureTask[5];
567 >            @SuppressWarnings("unchecked")
568 >            FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
569              for (int i = 0; i < tasks.length; i++) {
570 <                Callable task = new CheckedCallable<Boolean>() {
570 >                Callable<Boolean> task = new CheckedCallable<>() {
571                      public Boolean realCall() throws InterruptedException {
572                          threadStarted.countDown();
573                          assertSame(q, p.getQueue());
574 <                        done.await();
574 >                        await(done);
575                          return Boolean.TRUE;
576                      }};
577 <                tasks[i] = new FutureTask(task);
577 >                tasks[i] = new FutureTask<>(task);
578                  p.execute(tasks[i]);
579              }
580 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
580 >            await(threadStarted);
581              assertSame(q, p.getQueue());
582              assertFalse(q.contains(tasks[0]));
583              assertTrue(q.contains(tasks[tasks.length - 1]));
584              assertEquals(tasks.length - 1, q.size());
555        } finally {
556            done.countDown();
557            joinPool(p);
585          }
586      }
587  
# Line 562 | Line 589 | public class ThreadPoolExecutorTest exte
589       * remove(task) removes queued task, and fails to remove active task
590       */
591      public void testRemove() throws InterruptedException {
592 <        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
592 >        final CountDownLatch done = new CountDownLatch(1);
593 >        BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
594          final ThreadPoolExecutor p =
595              new ThreadPoolExecutor(1, 1,
596                                     LONG_DELAY_MS, MILLISECONDS,
597                                     q);
598 <        Runnable[] tasks = new Runnable[5];
599 <        final CountDownLatch threadStarted = new CountDownLatch(1);
600 <        final CountDownLatch done = new CountDownLatch(1);
573 <        try {
598 >        try (PoolCleaner cleaner = cleaner(p, done)) {
599 >            Runnable[] tasks = new Runnable[6];
600 >            final CountDownLatch threadStarted = new CountDownLatch(1);
601              for (int i = 0; i < tasks.length; i++) {
602                  tasks[i] = new CheckedRunnable() {
603                      public void realRun() throws InterruptedException {
604                          threadStarted.countDown();
605 <                        done.await();
605 >                        await(done);
606                      }};
607                  p.execute(tasks[i]);
608              }
609 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
609 >            await(threadStarted);
610              assertFalse(p.remove(tasks[0]));
611              assertTrue(q.contains(tasks[4]));
612              assertTrue(q.contains(tasks[3]));
# Line 589 | Line 616 | public class ThreadPoolExecutorTest exte
616              assertTrue(q.contains(tasks[3]));
617              assertTrue(p.remove(tasks[3]));
618              assertFalse(q.contains(tasks[3]));
592        } finally {
593            done.countDown();
594            joinPool(p);
619          }
620      }
621  
# Line 601 | Line 625 | public class ThreadPoolExecutorTest exte
625      public void testPurge() throws InterruptedException {
626          final CountDownLatch threadStarted = new CountDownLatch(1);
627          final CountDownLatch done = new CountDownLatch(1);
628 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
628 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
629          final ThreadPoolExecutor p =
630              new ThreadPoolExecutor(1, 1,
631                                     LONG_DELAY_MS, MILLISECONDS,
632                                     q);
633 <        FutureTask[] tasks = new FutureTask[5];
634 <        try {
633 >        try (PoolCleaner cleaner = cleaner(p, done)) {
634 >            FutureTask[] rtasks = new FutureTask[5];
635 >            @SuppressWarnings("unchecked")
636 >            FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
637              for (int i = 0; i < tasks.length; i++) {
638 <                Callable task = new CheckedCallable<Boolean>() {
638 >                Callable<Boolean> task = new CheckedCallable<>() {
639                      public Boolean realCall() throws InterruptedException {
640                          threadStarted.countDown();
641 <                        done.await();
641 >                        await(done);
642                          return Boolean.TRUE;
643                      }};
644 <                tasks[i] = new FutureTask(task);
644 >                tasks[i] = new FutureTask<>(task);
645                  p.execute(tasks[i]);
646              }
647 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
647 >            await(threadStarted);
648              assertEquals(tasks.length, p.getTaskCount());
649              assertEquals(tasks.length - 1, q.size());
650              assertEquals(1L, p.getActiveCount());
# Line 631 | Line 657 | public class ThreadPoolExecutorTest exte
657              p.purge();         // Nothing to do
658              assertEquals(tasks.length - 3, q.size());
659              assertEquals(tasks.length - 2, p.getTaskCount());
634        } finally {
635            done.countDown();
636            joinPool(p);
660          }
661      }
662  
# Line 649 | Line 672 | public class ThreadPoolExecutorTest exte
672              new ThreadPoolExecutor(poolSize, poolSize,
673                                     LONG_DELAY_MS, MILLISECONDS,
674                                     new ArrayBlockingQueue<Runnable>(10));
675 <        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
675 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
676          Runnable waiter = new CheckedRunnable() { public void realRun() {
677              threadsStarted.countDown();
678              try {
679 <                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
679 >                MILLISECONDS.sleep(LONGER_DELAY_MS);
680              } catch (InterruptedException success) {}
681              ran.getAndIncrement();
682          }};
683          for (int i = 0; i < count; i++)
684              p.execute(waiter);
685 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
685 >        await(threadsStarted);
686          assertEquals(poolSize, p.getActiveCount());
687          assertEquals(0, p.getCompletedTaskCount());
688          final List<Runnable> queuedTasks;
# Line 740 | Line 763 | public class ThreadPoolExecutorTest exte
763      public void testConstructorNullPointerException() {
764          try {
765              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
766 <                                   (BlockingQueue) null);
766 >                                   (BlockingQueue<Runnable>) null);
767              shouldThrow();
768          } catch (NullPointerException success) {}
769      }
# Line 811 | Line 834 | public class ThreadPoolExecutorTest exte
834      public void testConstructorNullPointerException2() {
835          try {
836              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
837 <                                   (BlockingQueue) null,
837 >                                   (BlockingQueue<Runnable>) null,
838                                     new SimpleThreadFactory());
839              shouldThrow();
840          } catch (NullPointerException success) {}
# Line 895 | Line 918 | public class ThreadPoolExecutorTest exte
918      public void testConstructorNullPointerException4() {
919          try {
920              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
921 <                                   (BlockingQueue) null,
921 >                                   (BlockingQueue<Runnable>) null,
922                                     new NoOpREHandler());
923              shouldThrow();
924          } catch (NullPointerException success) {}
# Line 984 | Line 1007 | public class ThreadPoolExecutorTest exte
1007      public void testConstructorNullPointerException6() {
1008          try {
1009              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1010 <                                   (BlockingQueue) null,
1010 >                                   (BlockingQueue<Runnable>) null,
1011                                     new SimpleThreadFactory(),
1012                                     new NoOpREHandler());
1013              shouldThrow();
# Line 1021 | Line 1044 | public class ThreadPoolExecutorTest exte
1044       * get of submitted callable throws InterruptedException if interrupted
1045       */
1046      public void testInterruptedSubmit() throws InterruptedException {
1047 +        final CountDownLatch done = new CountDownLatch(1);
1048          final ThreadPoolExecutor p =
1049              new ThreadPoolExecutor(1, 1,
1050                                     60, SECONDS,
1051                                     new ArrayBlockingQueue<Runnable>(10));
1052  
1053 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1054 <        final CountDownLatch done = new CountDownLatch(1);
1031 <        try {
1053 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1054 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1055              Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1056                  public void realRun() throws Exception {
1057 <                    Callable task = new CheckedCallable<Boolean>() {
1057 >                    Callable<Boolean> task = new CheckedCallable<>() {
1058                          public Boolean realCall() throws InterruptedException {
1059                              threadStarted.countDown();
1060 <                            done.await();
1060 >                            await(done);
1061                              return Boolean.TRUE;
1062                          }};
1063                      p.submit(task).get();
1064                  }});
1065  
1066 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
1066 >            await(threadStarted); // ensure quiescence
1067              t.interrupt();
1068 <            awaitTermination(t, MEDIUM_DELAY_MS);
1046 <        } finally {
1047 <            done.countDown();
1048 <            joinPool(p);
1068 >            awaitTermination(t);
1069          }
1070      }
1071  
1072      /**
1073 <     * execute throws RejectedExecutionException if saturated.
1073 >     * Submitted tasks are rejected when saturated or shutdown
1074       */
1075 <    public void testSaturatedExecute() {
1076 <        ThreadPoolExecutor p =
1077 <            new ThreadPoolExecutor(1, 1,
1078 <                                   LONG_DELAY_MS, MILLISECONDS,
1079 <                                   new ArrayBlockingQueue<Runnable>(1));
1075 >    public void testSubmittedTasksRejectedWhenSaturatedOrShutdown() throws InterruptedException {
1076 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1077 >            1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1078 >        final int saturatedSize = saturatedSize(p);
1079 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1080 >        final CountDownLatch threadsStarted = new CountDownLatch(p.getMaximumPoolSize());
1081          final CountDownLatch done = new CountDownLatch(1);
1082 <        try {
1083 <            Runnable task = new CheckedRunnable() {
1084 <                public void realRun() throws InterruptedException {
1064 <                    done.await();
1065 <                }};
1066 <            for (int i = 0; i < 2; ++i)
1067 <                p.execute(task);
1068 <            for (int i = 0; i < 2; ++i) {
1082 >        final Runnable r = () -> {
1083 >            threadsStarted.countDown();
1084 >            for (;;) {
1085                  try {
1070                    p.execute(task);
1071                    shouldThrow();
1072                } catch (RejectedExecutionException success) {}
1073                assertTrue(p.getTaskCount() <= 2);
1074            }
1075        } finally {
1076            done.countDown();
1077            joinPool(p);
1078        }
1079    }
1080
1081    /**
1082     * submit(runnable) throws RejectedExecutionException if saturated.
1083     */
1084    public void testSaturatedSubmitRunnable() {
1085        ThreadPoolExecutor p =
1086            new ThreadPoolExecutor(1, 1,
1087                                   LONG_DELAY_MS, MILLISECONDS,
1088                                   new ArrayBlockingQueue<Runnable>(1));
1089        final CountDownLatch done = new CountDownLatch(1);
1090        try {
1091            Runnable task = new CheckedRunnable() {
1092                public void realRun() throws InterruptedException {
1086                      done.await();
1087 <                }};
1088 <            for (int i = 0; i < 2; ++i)
1089 <                p.submit(task);
1090 <            for (int i = 0; i < 2; ++i) {
1087 >                    return;
1088 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1089 >            }};
1090 >        final Callable<Boolean> c = () -> {
1091 >            threadsStarted.countDown();
1092 >            for (;;) {
1093                  try {
1099                    p.execute(task);
1100                    shouldThrow();
1101                } catch (RejectedExecutionException success) {}
1102                assertTrue(p.getTaskCount() <= 2);
1103            }
1104        } finally {
1105            done.countDown();
1106            joinPool(p);
1107        }
1108    }
1109
1110    /**
1111     * submit(callable) throws RejectedExecutionException if saturated.
1112     */
1113    public void testSaturatedSubmitCallable() {
1114        ThreadPoolExecutor p =
1115            new ThreadPoolExecutor(1, 1,
1116                                   LONG_DELAY_MS, MILLISECONDS,
1117                                   new ArrayBlockingQueue<Runnable>(1));
1118        final CountDownLatch done = new CountDownLatch(1);
1119        try {
1120            Runnable task = new CheckedRunnable() {
1121                public void realRun() throws InterruptedException {
1094                      done.await();
1095 <                }};
1096 <            for (int i = 0; i < 2; ++i)
1097 <                p.submit(Executors.callable(task));
1098 <            for (int i = 0; i < 2; ++i) {
1099 <                try {
1100 <                    p.execute(task);
1101 <                    shouldThrow();
1102 <                } catch (RejectedExecutionException success) {}
1103 <                assertTrue(p.getTaskCount() <= 2);
1095 >                    return Boolean.TRUE;
1096 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1097 >            }};
1098 >        final boolean shutdownNow = rnd.nextBoolean();
1099 >
1100 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1101 >            // saturate
1102 >            for (int i = saturatedSize; i--> 0; ) {
1103 >                switch (rnd.nextInt(4)) {
1104 >                case 0: p.execute(r); break;
1105 >                case 1: assertFalse(p.submit(r).isDone()); break;
1106 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
1107 >                case 3: assertFalse(p.submit(c).isDone()); break;
1108 >                }
1109              }
1133        } finally {
1134            done.countDown();
1135            joinPool(p);
1136        }
1137    }
1110  
1111 <    /**
1112 <     * executor using CallerRunsPolicy runs task if saturated.
1141 <     */
1142 <    public void testSaturatedExecute2() {
1143 <        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1144 <        final ThreadPoolExecutor p =
1145 <            new ThreadPoolExecutor(1, 1,
1146 <                                   LONG_DELAY_MS,
1147 <                                   MILLISECONDS,
1148 <                                   new ArrayBlockingQueue<Runnable>(1),
1149 <                                   h);
1150 <        try {
1151 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1152 <            for (int i = 0; i < tasks.length; ++i)
1153 <                tasks[i] = new TrackedNoOpRunnable();
1154 <            TrackedLongRunnable mr = new TrackedLongRunnable();
1155 <            p.execute(mr);
1156 <            for (int i = 0; i < tasks.length; ++i)
1157 <                p.execute(tasks[i]);
1158 <            for (int i = 1; i < tasks.length; ++i)
1159 <                assertTrue(tasks[i].done);
1160 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1161 <        } finally {
1162 <            joinPool(p);
1163 <        }
1164 <    }
1111 >            await(threadsStarted);
1112 >            assertTaskSubmissionsAreRejected(p);
1113  
1114 <    /**
1115 <     * executor using DiscardPolicy drops task if saturated.
1116 <     */
1117 <    public void testSaturatedExecute3() {
1118 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1119 <        final ThreadPoolExecutor p =
1120 <            new ThreadPoolExecutor(1, 1,
1121 <                                   LONG_DELAY_MS, MILLISECONDS,
1122 <                                   new ArrayBlockingQueue<Runnable>(1),
1123 <                                   h);
1124 <        try {
1125 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1126 <            for (int i = 0; i < tasks.length; ++i)
1127 <                tasks[i] = new TrackedNoOpRunnable();
1128 <            p.execute(new TrackedLongRunnable());
1129 <            for (TrackedNoOpRunnable task : tasks)
1182 <                p.execute(task);
1183 <            for (TrackedNoOpRunnable task : tasks)
1184 <                assertFalse(task.done);
1185 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1186 <        } finally {
1187 <            joinPool(p);
1188 <        }
1114 >            if (shutdownNow)
1115 >                p.shutdownNow();
1116 >            else
1117 >                p.shutdown();
1118 >            // Pool is shutdown, but not yet terminated
1119 >            assertTaskSubmissionsAreRejected(p);
1120 >            assertFalse(p.isTerminated());
1121 >
1122 >            done.countDown();   // release blocking tasks
1123 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
1124 >
1125 >            assertTaskSubmissionsAreRejected(p);
1126 >        }
1127 >        assertEquals(saturatedSize(p)
1128 >                     - (shutdownNow ? p.getQueue().remainingCapacity() : 0),
1129 >                     p.getCompletedTaskCount());
1130      }
1131  
1132      /**
1133       * executor using DiscardOldestPolicy drops oldest task if saturated.
1134       */
1135 <    public void testSaturatedExecute4() {
1136 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1135 >    public void testSaturatedExecute_DiscardOldestPolicy() {
1136 >        final CountDownLatch done = new CountDownLatch(1);
1137 >        LatchAwaiter r1 = awaiter(done);
1138 >        LatchAwaiter r2 = awaiter(done);
1139 >        LatchAwaiter r3 = awaiter(done);
1140          final ThreadPoolExecutor p =
1141              new ThreadPoolExecutor(1, 1,
1142                                     LONG_DELAY_MS, MILLISECONDS,
1143                                     new ArrayBlockingQueue<Runnable>(1),
1144 <                                   h);
1145 <        try {
1146 <            p.execute(new TrackedLongRunnable());
1147 <            TrackedLongRunnable r2 = new TrackedLongRunnable();
1144 >                                   new DiscardOldestPolicy());
1145 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1146 >            assertEquals(LatchAwaiter.NEW, r1.state);
1147 >            assertEquals(LatchAwaiter.NEW, r2.state);
1148 >            assertEquals(LatchAwaiter.NEW, r3.state);
1149 >            p.execute(r1);
1150              p.execute(r2);
1151              assertTrue(p.getQueue().contains(r2));
1206            TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1152              p.execute(r3);
1153              assertFalse(p.getQueue().contains(r2));
1154              assertTrue(p.getQueue().contains(r3));
1210            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1211        } finally {
1212            joinPool(p);
1213        }
1214    }
1215
1216    /**
1217     * execute throws RejectedExecutionException if shutdown
1218     */
1219    public void testRejectedExecutionExceptionOnShutdown() {
1220        ThreadPoolExecutor p =
1221            new ThreadPoolExecutor(1, 1,
1222                                   LONG_DELAY_MS, MILLISECONDS,
1223                                   new ArrayBlockingQueue<Runnable>(1));
1224        try { p.shutdown(); } catch (SecurityException ok) { return; }
1225        try {
1226            p.execute(new NoOpRunnable());
1227            shouldThrow();
1228        } catch (RejectedExecutionException success) {}
1229
1230        joinPool(p);
1231    }
1232
1233    /**
1234     * execute using CallerRunsPolicy drops task on shutdown
1235     */
1236    public void testCallerRunsOnShutdown() {
1237        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1238        final ThreadPoolExecutor p =
1239            new ThreadPoolExecutor(1, 1,
1240                                   LONG_DELAY_MS, MILLISECONDS,
1241                                   new ArrayBlockingQueue<Runnable>(1), h);
1242
1243        try { p.shutdown(); } catch (SecurityException ok) { return; }
1244        try {
1245            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1246            p.execute(r);
1247            assertFalse(r.done);
1248        } finally {
1249            joinPool(p);
1250        }
1251    }
1252
1253    /**
1254     * execute using DiscardPolicy drops task on shutdown
1255     */
1256    public void testDiscardOnShutdown() {
1257        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1258        ThreadPoolExecutor p =
1259            new ThreadPoolExecutor(1, 1,
1260                                   LONG_DELAY_MS, MILLISECONDS,
1261                                   new ArrayBlockingQueue<Runnable>(1),
1262                                   h);
1263
1264        try { p.shutdown(); } catch (SecurityException ok) { return; }
1265        try {
1266            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1267            p.execute(r);
1268            assertFalse(r.done);
1269        } finally {
1270            joinPool(p);
1155          }
1156 +        assertEquals(LatchAwaiter.DONE, r1.state);
1157 +        assertEquals(LatchAwaiter.NEW, r2.state);
1158 +        assertEquals(LatchAwaiter.DONE, r3.state);
1159      }
1160  
1161      /**
1162       * execute using DiscardOldestPolicy drops task on shutdown
1163       */
1164      public void testDiscardOldestOnShutdown() {
1165 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1279 <        ThreadPoolExecutor p =
1165 >        final ThreadPoolExecutor p =
1166              new ThreadPoolExecutor(1, 1,
1167                                     LONG_DELAY_MS, MILLISECONDS,
1168                                     new ArrayBlockingQueue<Runnable>(1),
1169 <                                   h);
1169 >                                   new DiscardOldestPolicy());
1170  
1171          try { p.shutdown(); } catch (SecurityException ok) { return; }
1172 <        try {
1172 >        try (PoolCleaner cleaner = cleaner(p)) {
1173              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1174              p.execute(r);
1175              assertFalse(r.done);
1290        } finally {
1291            joinPool(p);
1176          }
1177      }
1178  
1179      /**
1180 <     * execute(null) throws NPE
1180 >     * Submitting null tasks throws NullPointerException
1181       */
1182 <    public void testExecuteNull() {
1183 <        ThreadPoolExecutor p =
1184 <            new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1182 >    public void testNullTaskSubmission() {
1183 >        final ThreadPoolExecutor p =
1184 >            new ThreadPoolExecutor(1, 2,
1185 >                                   1L, SECONDS,
1186                                     new ArrayBlockingQueue<Runnable>(10));
1187 <        try {
1188 <            p.execute(null);
1189 <            shouldThrow();
1305 <        } catch (NullPointerException success) {}
1306 <
1307 <        joinPool(p);
1187 >        try (PoolCleaner cleaner = cleaner(p)) {
1188 >            assertNullTaskSubmissionThrowsNullPointerException(p);
1189 >        }
1190      }
1191  
1192      /**
1193       * setCorePoolSize of negative value throws IllegalArgumentException
1194       */
1195      public void testCorePoolSizeIllegalArgumentException() {
1196 <        ThreadPoolExecutor p =
1196 >        final ThreadPoolExecutor p =
1197              new ThreadPoolExecutor(1, 2,
1198                                     LONG_DELAY_MS, MILLISECONDS,
1199                                     new ArrayBlockingQueue<Runnable>(10));
1200 <        try {
1201 <            p.setCorePoolSize(-1);
1202 <            shouldThrow();
1203 <        } catch (IllegalArgumentException success) {
1204 <        } finally {
1323 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1200 >        try (PoolCleaner cleaner = cleaner(p)) {
1201 >            try {
1202 >                p.setCorePoolSize(-1);
1203 >                shouldThrow();
1204 >            } catch (IllegalArgumentException success) {}
1205          }
1325        joinPool(p);
1206      }
1207  
1208      /**
# Line 1330 | Line 1210 | public class ThreadPoolExecutorTest exte
1210       * given a value less the core pool size
1211       */
1212      public void testMaximumPoolSizeIllegalArgumentException() {
1213 <        ThreadPoolExecutor p =
1213 >        final ThreadPoolExecutor p =
1214              new ThreadPoolExecutor(2, 3,
1215                                     LONG_DELAY_MS, MILLISECONDS,
1216                                     new ArrayBlockingQueue<Runnable>(10));
1217 <        try {
1218 <            p.setMaximumPoolSize(1);
1219 <            shouldThrow();
1220 <        } catch (IllegalArgumentException success) {
1221 <        } finally {
1342 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1217 >        try (PoolCleaner cleaner = cleaner(p)) {
1218 >            try {
1219 >                p.setMaximumPoolSize(1);
1220 >                shouldThrow();
1221 >            } catch (IllegalArgumentException success) {}
1222          }
1344        joinPool(p);
1223      }
1224  
1225      /**
# Line 1349 | Line 1227 | public class ThreadPoolExecutorTest exte
1227       * if given a negative value
1228       */
1229      public void testMaximumPoolSizeIllegalArgumentException2() {
1230 <        ThreadPoolExecutor p =
1230 >        final ThreadPoolExecutor p =
1231              new ThreadPoolExecutor(2, 3,
1232                                     LONG_DELAY_MS, MILLISECONDS,
1233                                     new ArrayBlockingQueue<Runnable>(10));
1234 <        try {
1235 <            p.setMaximumPoolSize(-1);
1236 <            shouldThrow();
1237 <        } catch (IllegalArgumentException success) {
1238 <        } finally {
1361 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1234 >        try (PoolCleaner cleaner = cleaner(p)) {
1235 >            try {
1236 >                p.setMaximumPoolSize(-1);
1237 >                shouldThrow();
1238 >            } catch (IllegalArgumentException success) {}
1239          }
1363        joinPool(p);
1240      }
1241  
1242      /**
# Line 1368 | Line 1244 | public class ThreadPoolExecutorTest exte
1244       * max pool size result in IllegalArgumentException.
1245       */
1246      public void testPoolSizeInvariants() {
1247 <        ThreadPoolExecutor p =
1247 >        final ThreadPoolExecutor p =
1248              new ThreadPoolExecutor(1, 1,
1249                                     LONG_DELAY_MS, MILLISECONDS,
1250                                     new ArrayBlockingQueue<Runnable>(10));
1251 <        for (int s = 1; s < 5; s++) {
1252 <            p.setMaximumPoolSize(s);
1253 <            p.setCorePoolSize(s);
1254 <            try {
1255 <                p.setMaximumPoolSize(s - 1);
1256 <                shouldThrow();
1257 <            } catch (IllegalArgumentException success) {}
1258 <            assertEquals(s, p.getCorePoolSize());
1259 <            assertEquals(s, p.getMaximumPoolSize());
1260 <            try {
1261 <                p.setCorePoolSize(s + 1);
1262 <                shouldThrow();
1263 <            } catch (IllegalArgumentException success) {}
1264 <            assertEquals(s, p.getCorePoolSize());
1265 <            assertEquals(s, p.getMaximumPoolSize());
1251 >        try (PoolCleaner cleaner = cleaner(p)) {
1252 >            for (int s = 1; s < 5; s++) {
1253 >                p.setMaximumPoolSize(s);
1254 >                p.setCorePoolSize(s);
1255 >                try {
1256 >                    p.setMaximumPoolSize(s - 1);
1257 >                    shouldThrow();
1258 >                } catch (IllegalArgumentException success) {}
1259 >                assertEquals(s, p.getCorePoolSize());
1260 >                assertEquals(s, p.getMaximumPoolSize());
1261 >                try {
1262 >                    p.setCorePoolSize(s + 1);
1263 >                    shouldThrow();
1264 >                } catch (IllegalArgumentException success) {}
1265 >                assertEquals(s, p.getCorePoolSize());
1266 >                assertEquals(s, p.getMaximumPoolSize());
1267 >            }
1268          }
1391        joinPool(p);
1269      }
1270  
1271      /**
# Line 1396 | Line 1273 | public class ThreadPoolExecutorTest exte
1273       * when given a negative value
1274       */
1275      public void testKeepAliveTimeIllegalArgumentException() {
1276 <        ThreadPoolExecutor p =
1276 >        final ThreadPoolExecutor p =
1277              new ThreadPoolExecutor(2, 3,
1278                                     LONG_DELAY_MS, MILLISECONDS,
1279                                     new ArrayBlockingQueue<Runnable>(10));
1280 <        try {
1281 <            p.setKeepAliveTime(-1,MILLISECONDS);
1282 <            shouldThrow();
1283 <        } catch (IllegalArgumentException success) {
1284 <        } finally {
1408 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1280 >        try (PoolCleaner cleaner = cleaner(p)) {
1281 >            try {
1282 >                p.setKeepAliveTime(-1, MILLISECONDS);
1283 >                shouldThrow();
1284 >            } catch (IllegalArgumentException success) {}
1285          }
1410        joinPool(p);
1286      }
1287  
1288      /**
# Line 1415 | Line 1290 | public class ThreadPoolExecutorTest exte
1290       */
1291      public void testTerminated() {
1292          ExtendedTPE p = new ExtendedTPE();
1293 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
1294 <        assertTrue(p.terminatedCalled());
1295 <        joinPool(p);
1293 >        try (PoolCleaner cleaner = cleaner(p)) {
1294 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
1295 >            assertTrue(p.terminatedCalled());
1296 >            assertTrue(p.isShutdown());
1297 >        }
1298      }
1299  
1300      /**
# Line 1425 | Line 1302 | public class ThreadPoolExecutorTest exte
1302       */
1303      public void testBeforeAfter() throws InterruptedException {
1304          ExtendedTPE p = new ExtendedTPE();
1305 <        try {
1305 >        try (PoolCleaner cleaner = cleaner(p)) {
1306              final CountDownLatch done = new CountDownLatch(1);
1307              p.execute(new CheckedRunnable() {
1308                  public void realRun() {
# Line 1435 | Line 1312 | public class ThreadPoolExecutorTest exte
1312              assertEquals(0, done.getCount());
1313              assertTrue(p.afterCalled());
1314              assertTrue(p.beforeCalled());
1438            try { p.shutdown(); } catch (SecurityException ok) { return; }
1439        } finally {
1440            joinPool(p);
1315          }
1316      }
1317  
# Line 1445 | Line 1319 | public class ThreadPoolExecutorTest exte
1319       * completed submit of callable returns result
1320       */
1321      public void testSubmitCallable() throws Exception {
1322 <        ExecutorService e =
1322 >        final ExecutorService e =
1323              new ThreadPoolExecutor(2, 2,
1324                                     LONG_DELAY_MS, MILLISECONDS,
1325                                     new ArrayBlockingQueue<Runnable>(10));
1326 <        try {
1326 >        try (PoolCleaner cleaner = cleaner(e)) {
1327              Future<String> future = e.submit(new StringTask());
1328              String result = future.get();
1329              assertSame(TEST_STRING, result);
1456        } finally {
1457            joinPool(e);
1330          }
1331      }
1332  
# Line 1462 | Line 1334 | public class ThreadPoolExecutorTest exte
1334       * completed submit of runnable returns successfully
1335       */
1336      public void testSubmitRunnable() throws Exception {
1337 <        ExecutorService e =
1337 >        final ExecutorService e =
1338              new ThreadPoolExecutor(2, 2,
1339                                     LONG_DELAY_MS, MILLISECONDS,
1340                                     new ArrayBlockingQueue<Runnable>(10));
1341 <        try {
1341 >        try (PoolCleaner cleaner = cleaner(e)) {
1342              Future<?> future = e.submit(new NoOpRunnable());
1343              future.get();
1344              assertTrue(future.isDone());
1473        } finally {
1474            joinPool(e);
1345          }
1346      }
1347  
# Line 1479 | Line 1349 | public class ThreadPoolExecutorTest exte
1349       * completed submit of (runnable, result) returns result
1350       */
1351      public void testSubmitRunnable2() throws Exception {
1352 <        ExecutorService e =
1352 >        final ExecutorService e =
1353              new ThreadPoolExecutor(2, 2,
1354                                     LONG_DELAY_MS, MILLISECONDS,
1355                                     new ArrayBlockingQueue<Runnable>(10));
1356 <        try {
1356 >        try (PoolCleaner cleaner = cleaner(e)) {
1357              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1358              String result = future.get();
1359              assertSame(TEST_STRING, result);
1490        } finally {
1491            joinPool(e);
1360          }
1361      }
1362  
# Line 1496 | Line 1364 | public class ThreadPoolExecutorTest exte
1364       * invokeAny(null) throws NPE
1365       */
1366      public void testInvokeAny1() throws Exception {
1367 <        ExecutorService e =
1367 >        final ExecutorService e =
1368              new ThreadPoolExecutor(2, 2,
1369                                     LONG_DELAY_MS, MILLISECONDS,
1370                                     new ArrayBlockingQueue<Runnable>(10));
1371 <        try {
1372 <            e.invokeAny(null);
1373 <            shouldThrow();
1374 <        } catch (NullPointerException success) {
1375 <        } finally {
1508 <            joinPool(e);
1371 >        try (PoolCleaner cleaner = cleaner(e)) {
1372 >            try {
1373 >                e.invokeAny(null);
1374 >                shouldThrow();
1375 >            } catch (NullPointerException success) {}
1376          }
1377      }
1378  
1379      /**
1380 <     * invokeAny(empty collection) throws IAE
1380 >     * invokeAny(empty collection) throws IllegalArgumentException
1381       */
1382      public void testInvokeAny2() throws Exception {
1383 <        ExecutorService e =
1383 >        final ExecutorService e =
1384              new ThreadPoolExecutor(2, 2,
1385                                     LONG_DELAY_MS, MILLISECONDS,
1386                                     new ArrayBlockingQueue<Runnable>(10));
1387 <        try {
1388 <            e.invokeAny(new ArrayList<Callable<String>>());
1389 <            shouldThrow();
1390 <        } catch (IllegalArgumentException success) {
1391 <        } finally {
1525 <            joinPool(e);
1387 >        try (PoolCleaner cleaner = cleaner(e)) {
1388 >            try {
1389 >                e.invokeAny(new ArrayList<Callable<String>>());
1390 >                shouldThrow();
1391 >            } catch (IllegalArgumentException success) {}
1392          }
1393      }
1394  
# Line 1535 | Line 1401 | public class ThreadPoolExecutorTest exte
1401              new ThreadPoolExecutor(2, 2,
1402                                     LONG_DELAY_MS, MILLISECONDS,
1403                                     new ArrayBlockingQueue<Runnable>(10));
1404 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1405 <        l.add(latchAwaitingStringTask(latch));
1406 <        l.add(null);
1407 <        try {
1408 <            e.invokeAny(l);
1409 <            shouldThrow();
1410 <        } catch (NullPointerException success) {
1411 <        } finally {
1404 >        try (PoolCleaner cleaner = cleaner(e)) {
1405 >            List<Callable<String>> l = new ArrayList<>();
1406 >            l.add(latchAwaitingStringTask(latch));
1407 >            l.add(null);
1408 >            try {
1409 >                e.invokeAny(l);
1410 >                shouldThrow();
1411 >            } catch (NullPointerException success) {}
1412              latch.countDown();
1547            joinPool(e);
1413          }
1414      }
1415  
# Line 1552 | Line 1417 | public class ThreadPoolExecutorTest exte
1417       * invokeAny(c) throws ExecutionException if no task completes
1418       */
1419      public void testInvokeAny4() throws Exception {
1420 <        ExecutorService e =
1420 >        final ExecutorService e =
1421              new ThreadPoolExecutor(2, 2,
1422                                     LONG_DELAY_MS, MILLISECONDS,
1423                                     new ArrayBlockingQueue<Runnable>(10));
1424 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1425 <        l.add(new NPETask());
1426 <        try {
1427 <            e.invokeAny(l);
1428 <            shouldThrow();
1429 <        } catch (ExecutionException success) {
1430 <            assertTrue(success.getCause() instanceof NullPointerException);
1431 <        } finally {
1432 <            joinPool(e);
1424 >        try (PoolCleaner cleaner = cleaner(e)) {
1425 >            List<Callable<String>> l = new ArrayList<>();
1426 >            l.add(new NPETask());
1427 >            try {
1428 >                e.invokeAny(l);
1429 >                shouldThrow();
1430 >            } catch (ExecutionException success) {
1431 >                assertTrue(success.getCause() instanceof NullPointerException);
1432 >            }
1433          }
1434      }
1435  
# Line 1572 | Line 1437 | public class ThreadPoolExecutorTest exte
1437       * invokeAny(c) returns result of some task
1438       */
1439      public void testInvokeAny5() throws Exception {
1440 <        ExecutorService e =
1440 >        final ExecutorService e =
1441              new ThreadPoolExecutor(2, 2,
1442                                     LONG_DELAY_MS, MILLISECONDS,
1443                                     new ArrayBlockingQueue<Runnable>(10));
1444 <        try {
1445 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1444 >        try (PoolCleaner cleaner = cleaner(e)) {
1445 >            List<Callable<String>> l = new ArrayList<>();
1446              l.add(new StringTask());
1447              l.add(new StringTask());
1448              String result = e.invokeAny(l);
1449              assertSame(TEST_STRING, result);
1585        } finally {
1586            joinPool(e);
1450          }
1451      }
1452  
# Line 1591 | Line 1454 | public class ThreadPoolExecutorTest exte
1454       * invokeAll(null) throws NPE
1455       */
1456      public void testInvokeAll1() throws Exception {
1457 <        ExecutorService e =
1457 >        final ExecutorService e =
1458              new ThreadPoolExecutor(2, 2,
1459                                     LONG_DELAY_MS, MILLISECONDS,
1460                                     new ArrayBlockingQueue<Runnable>(10));
1461 <        try {
1462 <            e.invokeAll(null);
1463 <            shouldThrow();
1464 <        } catch (NullPointerException success) {
1465 <        } finally {
1603 <            joinPool(e);
1461 >        try (PoolCleaner cleaner = cleaner(e)) {
1462 >            try {
1463 >                e.invokeAll(null);
1464 >                shouldThrow();
1465 >            } catch (NullPointerException success) {}
1466          }
1467      }
1468  
1469      /**
1470 <     * invokeAll(empty collection) returns empty collection
1470 >     * invokeAll(empty collection) returns empty list
1471       */
1472      public void testInvokeAll2() throws InterruptedException {
1473 <        ExecutorService e =
1473 >        final ExecutorService e =
1474              new ThreadPoolExecutor(2, 2,
1475                                     LONG_DELAY_MS, MILLISECONDS,
1476                                     new ArrayBlockingQueue<Runnable>(10));
1477 <        try {
1478 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1477 >        final Collection<Callable<String>> emptyCollection
1478 >            = Collections.emptyList();
1479 >        try (PoolCleaner cleaner = cleaner(e)) {
1480 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1481              assertTrue(r.isEmpty());
1618        } finally {
1619            joinPool(e);
1482          }
1483      }
1484  
# Line 1624 | Line 1486 | public class ThreadPoolExecutorTest exte
1486       * invokeAll(c) throws NPE if c has null elements
1487       */
1488      public void testInvokeAll3() throws Exception {
1489 <        ExecutorService e =
1489 >        final ExecutorService e =
1490              new ThreadPoolExecutor(2, 2,
1491                                     LONG_DELAY_MS, MILLISECONDS,
1492                                     new ArrayBlockingQueue<Runnable>(10));
1493 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1494 <        l.add(new StringTask());
1495 <        l.add(null);
1496 <        try {
1497 <            e.invokeAll(l);
1498 <            shouldThrow();
1499 <        } catch (NullPointerException success) {
1500 <        } finally {
1639 <            joinPool(e);
1493 >        try (PoolCleaner cleaner = cleaner(e)) {
1494 >            List<Callable<String>> l = new ArrayList<>();
1495 >            l.add(new StringTask());
1496 >            l.add(null);
1497 >            try {
1498 >                e.invokeAll(l);
1499 >                shouldThrow();
1500 >            } catch (NullPointerException success) {}
1501          }
1502      }
1503  
# Line 1644 | Line 1505 | public class ThreadPoolExecutorTest exte
1505       * get of element of invokeAll(c) throws exception on failed task
1506       */
1507      public void testInvokeAll4() throws Exception {
1508 <        ExecutorService e =
1508 >        final ExecutorService e =
1509              new ThreadPoolExecutor(2, 2,
1510                                     LONG_DELAY_MS, MILLISECONDS,
1511                                     new ArrayBlockingQueue<Runnable>(10));
1512 <        try {
1513 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1512 >        try (PoolCleaner cleaner = cleaner(e)) {
1513 >            List<Callable<String>> l = new ArrayList<>();
1514              l.add(new NPETask());
1515              List<Future<String>> futures = e.invokeAll(l);
1516              assertEquals(1, futures.size());
# Line 1659 | Line 1520 | public class ThreadPoolExecutorTest exte
1520              } catch (ExecutionException success) {
1521                  assertTrue(success.getCause() instanceof NullPointerException);
1522              }
1662        } finally {
1663            joinPool(e);
1523          }
1524      }
1525  
# Line 1668 | Line 1527 | public class ThreadPoolExecutorTest exte
1527       * invokeAll(c) returns results of all completed tasks
1528       */
1529      public void testInvokeAll5() throws Exception {
1530 <        ExecutorService e =
1530 >        final ExecutorService e =
1531              new ThreadPoolExecutor(2, 2,
1532                                     LONG_DELAY_MS, MILLISECONDS,
1533                                     new ArrayBlockingQueue<Runnable>(10));
1534 <        try {
1535 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1534 >        try (PoolCleaner cleaner = cleaner(e)) {
1535 >            List<Callable<String>> l = new ArrayList<>();
1536              l.add(new StringTask());
1537              l.add(new StringTask());
1538              List<Future<String>> futures = e.invokeAll(l);
1539              assertEquals(2, futures.size());
1540              for (Future<String> future : futures)
1541                  assertSame(TEST_STRING, future.get());
1683        } finally {
1684            joinPool(e);
1542          }
1543      }
1544  
# Line 1689 | Line 1546 | public class ThreadPoolExecutorTest exte
1546       * timed invokeAny(null) throws NPE
1547       */
1548      public void testTimedInvokeAny1() throws Exception {
1549 <        ExecutorService e =
1549 >        final ExecutorService e =
1550              new ThreadPoolExecutor(2, 2,
1551                                     LONG_DELAY_MS, MILLISECONDS,
1552                                     new ArrayBlockingQueue<Runnable>(10));
1553 <        try {
1554 <            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1555 <            shouldThrow();
1556 <        } catch (NullPointerException success) {
1557 <        } finally {
1701 <            joinPool(e);
1553 >        try (PoolCleaner cleaner = cleaner(e)) {
1554 >            try {
1555 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1556 >                shouldThrow();
1557 >            } catch (NullPointerException success) {}
1558          }
1559      }
1560  
# Line 1706 | Line 1562 | public class ThreadPoolExecutorTest exte
1562       * timed invokeAny(,,null) throws NPE
1563       */
1564      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1565 <        ExecutorService e =
1565 >        final ExecutorService e =
1566              new ThreadPoolExecutor(2, 2,
1567                                     LONG_DELAY_MS, MILLISECONDS,
1568                                     new ArrayBlockingQueue<Runnable>(10));
1569 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1570 <        l.add(new StringTask());
1571 <        try {
1572 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
1573 <            shouldThrow();
1574 <        } catch (NullPointerException success) {
1575 <        } finally {
1720 <            joinPool(e);
1569 >        try (PoolCleaner cleaner = cleaner(e)) {
1570 >            List<Callable<String>> l = new ArrayList<>();
1571 >            l.add(new StringTask());
1572 >            try {
1573 >                e.invokeAny(l, randomTimeout(), null);
1574 >                shouldThrow();
1575 >            } catch (NullPointerException success) {}
1576          }
1577      }
1578  
1579      /**
1580 <     * timed invokeAny(empty collection) throws IAE
1580 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1581       */
1582      public void testTimedInvokeAny2() throws Exception {
1583 <        ExecutorService e =
1583 >        final ExecutorService e =
1584              new ThreadPoolExecutor(2, 2,
1585                                     LONG_DELAY_MS, MILLISECONDS,
1586                                     new ArrayBlockingQueue<Runnable>(10));
1587 <        try {
1588 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1589 <            shouldThrow();
1590 <        } catch (IllegalArgumentException success) {
1591 <        } finally {
1592 <            joinPool(e);
1587 >        try (PoolCleaner cleaner = cleaner(e)) {
1588 >            try {
1589 >                e.invokeAny(new ArrayList<Callable<String>>(),
1590 >                            randomTimeout(), randomTimeUnit());
1591 >                shouldThrow();
1592 >            } catch (IllegalArgumentException success) {}
1593          }
1594      }
1595  
1596      /**
1597 <     * timed invokeAny(c) throws NPE if c has null elements
1597 >     * timed invokeAny(c) throws NullPointerException if c has null elements
1598       */
1599      public void testTimedInvokeAny3() throws Exception {
1600          final CountDownLatch latch = new CountDownLatch(1);
# Line 1747 | Line 1602 | public class ThreadPoolExecutorTest exte
1602              new ThreadPoolExecutor(2, 2,
1603                                     LONG_DELAY_MS, MILLISECONDS,
1604                                     new ArrayBlockingQueue<Runnable>(10));
1605 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1606 <        l.add(latchAwaitingStringTask(latch));
1607 <        l.add(null);
1608 <        try {
1609 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1610 <            shouldThrow();
1611 <        } catch (NullPointerException success) {
1612 <        } finally {
1605 >        try (PoolCleaner cleaner = cleaner(e)) {
1606 >            List<Callable<String>> l = new ArrayList<>();
1607 >            l.add(latchAwaitingStringTask(latch));
1608 >            l.add(null);
1609 >            try {
1610 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1611 >                shouldThrow();
1612 >            } catch (NullPointerException success) {}
1613              latch.countDown();
1759            joinPool(e);
1614          }
1615      }
1616  
# Line 1764 | Line 1618 | public class ThreadPoolExecutorTest exte
1618       * timed invokeAny(c) throws ExecutionException if no task completes
1619       */
1620      public void testTimedInvokeAny4() throws Exception {
1621 <        ExecutorService e =
1621 >        final ExecutorService e =
1622              new ThreadPoolExecutor(2, 2,
1623                                     LONG_DELAY_MS, MILLISECONDS,
1624                                     new ArrayBlockingQueue<Runnable>(10));
1625 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1626 <        l.add(new NPETask());
1627 <        try {
1628 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1629 <            shouldThrow();
1630 <        } catch (ExecutionException success) {
1631 <            assertTrue(success.getCause() instanceof NullPointerException);
1632 <        } finally {
1633 <            joinPool(e);
1625 >        try (PoolCleaner cleaner = cleaner(e)) {
1626 >            long startTime = System.nanoTime();
1627 >            List<Callable<String>> l = new ArrayList<>();
1628 >            l.add(new NPETask());
1629 >            try {
1630 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1631 >                shouldThrow();
1632 >            } catch (ExecutionException success) {
1633 >                assertTrue(success.getCause() instanceof NullPointerException);
1634 >            }
1635 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1636          }
1637      }
1638  
# Line 1784 | Line 1640 | public class ThreadPoolExecutorTest exte
1640       * timed invokeAny(c) returns result of some task
1641       */
1642      public void testTimedInvokeAny5() throws Exception {
1643 <        ExecutorService e =
1643 >        final 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>>();
1647 >        try (PoolCleaner cleaner = cleaner(e)) {
1648 >            long startTime = System.nanoTime();
1649 >            List<Callable<String>> l = new ArrayList<>();
1650              l.add(new StringTask());
1651              l.add(new StringTask());
1652 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1652 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1653              assertSame(TEST_STRING, result);
1654 <        } finally {
1798 <            joinPool(e);
1654 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1655          }
1656      }
1657  
# Line 1803 | Line 1659 | public class ThreadPoolExecutorTest exte
1659       * timed invokeAll(null) throws NPE
1660       */
1661      public void testTimedInvokeAll1() throws Exception {
1662 <        ExecutorService e =
1662 >        final ExecutorService e =
1663              new ThreadPoolExecutor(2, 2,
1664                                     LONG_DELAY_MS, MILLISECONDS,
1665                                     new ArrayBlockingQueue<Runnable>(10));
1666 <        try {
1667 <            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1668 <            shouldThrow();
1669 <        } catch (NullPointerException success) {
1670 <        } finally {
1815 <            joinPool(e);
1666 >        try (PoolCleaner cleaner = cleaner(e)) {
1667 >            try {
1668 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1669 >                shouldThrow();
1670 >            } catch (NullPointerException success) {}
1671          }
1672      }
1673  
# Line 1820 | Line 1675 | public class ThreadPoolExecutorTest exte
1675       * timed invokeAll(,,null) throws NPE
1676       */
1677      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1678 <        ExecutorService e =
1678 >        final ExecutorService e =
1679              new ThreadPoolExecutor(2, 2,
1680                                     LONG_DELAY_MS, MILLISECONDS,
1681                                     new ArrayBlockingQueue<Runnable>(10));
1682 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1683 <        l.add(new StringTask());
1684 <        try {
1685 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1686 <            shouldThrow();
1687 <        } catch (NullPointerException success) {
1688 <        } finally {
1834 <            joinPool(e);
1682 >        try (PoolCleaner cleaner = cleaner(e)) {
1683 >            List<Callable<String>> l = new ArrayList<>();
1684 >            l.add(new StringTask());
1685 >            try {
1686 >                e.invokeAll(l, randomTimeout(), null);
1687 >                shouldThrow();
1688 >            } catch (NullPointerException success) {}
1689          }
1690      }
1691  
1692      /**
1693 <     * timed invokeAll(empty collection) returns empty collection
1693 >     * timed invokeAll(empty collection) returns empty list
1694       */
1695      public void testTimedInvokeAll2() throws InterruptedException {
1696 <        ExecutorService e =
1696 >        final ExecutorService e =
1697              new ThreadPoolExecutor(2, 2,
1698                                     LONG_DELAY_MS, MILLISECONDS,
1699                                     new ArrayBlockingQueue<Runnable>(10));
1700 <        try {
1701 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1700 >        final Collection<Callable<String>> emptyCollection
1701 >            = Collections.emptyList();
1702 >        try (PoolCleaner cleaner = cleaner(e)) {
1703 >            List<Future<String>> r =
1704 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1705              assertTrue(r.isEmpty());
1849        } finally {
1850            joinPool(e);
1706          }
1707      }
1708  
# Line 1855 | Line 1710 | public class ThreadPoolExecutorTest exte
1710       * timed invokeAll(c) throws NPE if c has null elements
1711       */
1712      public void testTimedInvokeAll3() throws Exception {
1713 <        ExecutorService e =
1713 >        final ExecutorService e =
1714              new ThreadPoolExecutor(2, 2,
1715                                     LONG_DELAY_MS, MILLISECONDS,
1716                                     new ArrayBlockingQueue<Runnable>(10));
1717 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1718 <        l.add(new StringTask());
1719 <        l.add(null);
1720 <        try {
1721 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1722 <            shouldThrow();
1723 <        } catch (NullPointerException success) {
1724 <        } finally {
1870 <            joinPool(e);
1717 >        try (PoolCleaner cleaner = cleaner(e)) {
1718 >            List<Callable<String>> l = new ArrayList<>();
1719 >            l.add(new StringTask());
1720 >            l.add(null);
1721 >            try {
1722 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1723 >                shouldThrow();
1724 >            } catch (NullPointerException success) {}
1725          }
1726      }
1727  
# Line 1875 | Line 1729 | public class ThreadPoolExecutorTest exte
1729       * get of element of invokeAll(c) throws exception on failed task
1730       */
1731      public void testTimedInvokeAll4() throws Exception {
1732 <        ExecutorService e =
1732 >        final ExecutorService e =
1733              new ThreadPoolExecutor(2, 2,
1734                                     LONG_DELAY_MS, MILLISECONDS,
1735                                     new ArrayBlockingQueue<Runnable>(10));
1736 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1737 <        l.add(new NPETask());
1738 <        List<Future<String>> futures =
1739 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1740 <        assertEquals(1, futures.size());
1741 <        try {
1742 <            futures.get(0).get();
1743 <            shouldThrow();
1744 <        } catch (ExecutionException success) {
1745 <            assertTrue(success.getCause() instanceof NullPointerException);
1746 <        } finally {
1747 <            joinPool(e);
1736 >        try (PoolCleaner cleaner = cleaner(e)) {
1737 >            List<Callable<String>> l = new ArrayList<>();
1738 >            l.add(new NPETask());
1739 >            List<Future<String>> futures =
1740 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1741 >            assertEquals(1, futures.size());
1742 >            try {
1743 >                futures.get(0).get();
1744 >                shouldThrow();
1745 >            } catch (ExecutionException success) {
1746 >                assertTrue(success.getCause() instanceof NullPointerException);
1747 >            }
1748          }
1749      }
1750  
# Line 1898 | Line 1752 | public class ThreadPoolExecutorTest exte
1752       * timed invokeAll(c) returns results of all completed tasks
1753       */
1754      public void testTimedInvokeAll5() throws Exception {
1755 <        ExecutorService e =
1755 >        final ExecutorService e =
1756              new ThreadPoolExecutor(2, 2,
1757                                     LONG_DELAY_MS, MILLISECONDS,
1758                                     new ArrayBlockingQueue<Runnable>(10));
1759 <        try {
1760 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1759 >        try (PoolCleaner cleaner = cleaner(e)) {
1760 >            List<Callable<String>> l = new ArrayList<>();
1761              l.add(new StringTask());
1762              l.add(new StringTask());
1763              List<Future<String>> futures =
# Line 1911 | Line 1765 | public class ThreadPoolExecutorTest exte
1765              assertEquals(2, futures.size());
1766              for (Future<String> future : futures)
1767                  assertSame(TEST_STRING, future.get());
1914        } finally {
1915            joinPool(e);
1768          }
1769      }
1770  
# Line 1920 | Line 1772 | public class ThreadPoolExecutorTest exte
1772       * timed invokeAll(c) cancels tasks not completed by timeout
1773       */
1774      public void testTimedInvokeAll6() throws Exception {
1775 <        ExecutorService e =
1776 <            new ThreadPoolExecutor(2, 2,
1777 <                                   LONG_DELAY_MS, MILLISECONDS,
1778 <                                   new ArrayBlockingQueue<Runnable>(10));
1779 <        try {
1780 <            for (long timeout = timeoutMillis();;) {
1775 >        for (long timeout = timeoutMillis();;) {
1776 >            final CountDownLatch done = new CountDownLatch(1);
1777 >            final Callable<String> waiter = new CheckedCallable<>() {
1778 >                public String realCall() {
1779 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1780 >                    catch (InterruptedException ok) {}
1781 >                    return "1"; }};
1782 >            final ExecutorService p =
1783 >                new ThreadPoolExecutor(2, 2,
1784 >                                       LONG_DELAY_MS, MILLISECONDS,
1785 >                                       new ArrayBlockingQueue<Runnable>(10));
1786 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1787                  List<Callable<String>> tasks = new ArrayList<>();
1788                  tasks.add(new StringTask("0"));
1789 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1789 >                tasks.add(waiter);
1790                  tasks.add(new StringTask("2"));
1791                  long startTime = System.nanoTime();
1792                  List<Future<String>> futures =
1793 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1793 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1794                  assertEquals(tasks.size(), futures.size());
1795                  assertTrue(millisElapsedSince(startTime) >= timeout);
1796 <                for (Future future : futures)
1796 >                for (Future<?> future : futures)
1797                      assertTrue(future.isDone());
1798                  assertTrue(futures.get(1).isCancelled());
1799                  try {
# Line 1948 | Line 1806 | public class ThreadPoolExecutorTest exte
1806                          fail("expected exactly one task to be cancelled");
1807                  }
1808              }
1951        } finally {
1952            joinPool(e);
1809          }
1810      }
1811  
# Line 1963 | Line 1819 | public class ThreadPoolExecutorTest exte
1819                                     LONG_DELAY_MS, MILLISECONDS,
1820                                     new LinkedBlockingQueue<Runnable>(),
1821                                     new FailingThreadFactory());
1822 <        try {
1822 >        try (PoolCleaner cleaner = cleaner(e)) {
1823              final int TASKS = 100;
1824              final CountDownLatch done = new CountDownLatch(TASKS);
1825              for (int k = 0; k < TASKS; ++k)
# Line 1971 | Line 1827 | public class ThreadPoolExecutorTest exte
1827                      public void realRun() {
1828                          done.countDown();
1829                      }});
1830 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1975 <        } finally {
1976 <            joinPool(e);
1830 >            await(done);
1831          }
1832      }
1833  
# Line 1985 | Line 1839 | public class ThreadPoolExecutorTest exte
1839              new ThreadPoolExecutor(2, 2,
1840                                     1000, MILLISECONDS,
1841                                     new ArrayBlockingQueue<Runnable>(10));
1842 <        assertFalse(p.allowsCoreThreadTimeOut());
1843 <        joinPool(p);
1842 >        try (PoolCleaner cleaner = cleaner(p)) {
1843 >            assertFalse(p.allowsCoreThreadTimeOut());
1844 >        }
1845      }
1846  
1847      /**
# Line 1998 | Line 1853 | public class ThreadPoolExecutorTest exte
1853              new ThreadPoolExecutor(2, 10,
1854                                     keepAliveTime, MILLISECONDS,
1855                                     new ArrayBlockingQueue<Runnable>(10));
1856 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1857 <        try {
1856 >        try (PoolCleaner cleaner = cleaner(p)) {
1857 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1858              p.allowCoreThreadTimeOut(true);
1859              p.execute(new CheckedRunnable() {
1860                  public void realRun() {
# Line 2014 | Line 1869 | public class ThreadPoolExecutorTest exte
1869                  Thread.yield();
1870              assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1871              assertEquals(0, p.getPoolSize());
2017        } finally {
2018            joinPool(p);
1872          }
1873      }
1874  
# Line 2028 | Line 1881 | public class ThreadPoolExecutorTest exte
1881              new ThreadPoolExecutor(2, 10,
1882                                     keepAliveTime, MILLISECONDS,
1883                                     new ArrayBlockingQueue<Runnable>(10));
1884 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1885 <        try {
1884 >        try (PoolCleaner cleaner = cleaner(p)) {
1885 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1886              p.allowCoreThreadTimeOut(false);
1887              p.execute(new CheckedRunnable() {
1888                  public void realRun() throws InterruptedException {
# Line 2038 | Line 1891 | public class ThreadPoolExecutorTest exte
1891                  }});
1892              delay(2 * keepAliveTime);
1893              assertTrue(p.getPoolSize() >= 1);
2041        } finally {
2042            joinPool(p);
1894          }
1895      }
1896  
# Line 2057 | Line 1908 | public class ThreadPoolExecutorTest exte
1908          final ThreadPoolExecutor p =
1909              new ThreadPoolExecutor(1, 30,
1910                                     60, SECONDS,
1911 <                                   new ArrayBlockingQueue(30));
1912 <        try {
1911 >                                   new ArrayBlockingQueue<Runnable>(30));
1912 >        try (PoolCleaner cleaner = cleaner(p)) {
1913              for (int i = 0; i < nTasks; ++i) {
1914                  for (;;) {
1915                      try {
# Line 2069 | Line 1920 | public class ThreadPoolExecutorTest exte
1920                  }
1921              }
1922              // enough time to run all tasks
1923 <            assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2073 <        } finally {
2074 <            joinPool(p);
1923 >            await(done, nTasks * SHORT_DELAY_MS);
1924          }
1925      }
1926  
# Line 2079 | Line 1928 | public class ThreadPoolExecutorTest exte
1928       * get(cancelled task) throws CancellationException
1929       */
1930      public void testGet_cancelled() throws Exception {
1931 +        final CountDownLatch done = new CountDownLatch(1);
1932          final ExecutorService e =
1933              new ThreadPoolExecutor(1, 1,
1934                                     LONG_DELAY_MS, MILLISECONDS,
1935                                     new LinkedBlockingQueue<Runnable>());
1936 <        try {
1936 >        try (PoolCleaner cleaner = cleaner(e, done)) {
1937              final CountDownLatch blockerStarted = new CountDownLatch(1);
2088            final CountDownLatch done = new CountDownLatch(1);
1938              final List<Future<?>> futures = new ArrayList<>();
1939              for (int i = 0; i < 2; i++) {
1940                  Runnable r = new CheckedRunnable() { public void realRun()
# Line 2095 | Line 1944 | public class ThreadPoolExecutorTest exte
1944                  }};
1945                  futures.add(e.submit(r));
1946              }
1947 <            assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
1947 >            await(blockerStarted);
1948              for (Future<?> future : futures) future.cancel(false);
1949              for (Future<?> future : futures) {
1950                  try {
# Line 2109 | Line 1958 | public class ThreadPoolExecutorTest exte
1958                  assertTrue(future.isCancelled());
1959                  assertTrue(future.isDone());
1960              }
1961 <            done.countDown();
1962 <        } finally {
1963 <            joinPool(e);
1961 >        }
1962 >    }
1963 >
1964 >    /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
1965 >    public void testStandardRejectedExecutionHandlers() {
1966 >        final ThreadPoolExecutor p =
1967 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
1968 >                                   new ArrayBlockingQueue<Runnable>(1));
1969 >        final AtomicReference<Thread> thread = new AtomicReference<>();
1970 >        final Runnable r = new Runnable() { public void run() {
1971 >            thread.set(Thread.currentThread()); }};
1972 >
1973 >        try {
1974 >            new AbortPolicy().rejectedExecution(r, p);
1975 >            shouldThrow();
1976 >        } catch (RejectedExecutionException success) {}
1977 >        assertNull(thread.get());
1978 >
1979 >        new DiscardPolicy().rejectedExecution(r, p);
1980 >        assertNull(thread.get());
1981 >
1982 >        new CallerRunsPolicy().rejectedExecution(r, p);
1983 >        assertSame(Thread.currentThread(), thread.get());
1984 >
1985 >        // check that pool was not perturbed by handlers
1986 >        assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1987 >        assertEquals(0, p.getTaskCount());
1988 >        assertTrue(p.getQueue().isEmpty());
1989 >    }
1990 >
1991 >    public void testThreadFactoryReturnsTerminatedThread_shouldThrow() {
1992 >        if (!testImplementationDetails)
1993 >            return;
1994 >
1995 >        ThreadFactory returnsTerminatedThread = runnableIgnored -> {
1996 >            Thread thread = new Thread(() -> {});
1997 >            thread.start();
1998 >            try { thread.join(); }
1999 >            catch (InterruptedException ex) { throw new Error(ex); }
2000 >            return thread;
2001 >        };
2002 >        ThreadPoolExecutor p =
2003 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2004 >                                   new ArrayBlockingQueue<Runnable>(1),
2005 >                                   returnsTerminatedThread);
2006 >        try (PoolCleaner cleaner = cleaner(p)) {
2007 >            assertThrows(IllegalThreadStateException.class,
2008 >                         () -> p.execute(() -> {}));
2009 >        }
2010 >    }
2011 >
2012 >    public void testThreadFactoryReturnsStartedThread_shouldThrow() {
2013 >        if (!testImplementationDetails)
2014 >            return;
2015 >
2016 >        CountDownLatch latch = new CountDownLatch(1);
2017 >        Runnable awaitLatch = () -> {
2018 >            try { latch.await(); }
2019 >            catch (InterruptedException ex) { throw new Error(ex); }};
2020 >        ThreadFactory returnsStartedThread = runnable -> {
2021 >            Thread thread = new Thread(awaitLatch);
2022 >            thread.start();
2023 >            return thread;
2024 >        };
2025 >        ThreadPoolExecutor p =
2026 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2027 >                                   new ArrayBlockingQueue<Runnable>(1),
2028 >                                   returnsStartedThread);
2029 >        try (PoolCleaner cleaner = cleaner(p)) {
2030 >            assertThrows(IllegalThreadStateException.class,
2031 >                         () -> p.execute(() -> {}));
2032 >            latch.countDown();
2033          }
2034      }
2035  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines