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.52 by jsr166, Fri May 15 17:07:27 2015 UTC vs.
Revision 1.122 by jsr166, Sat Jul 15 18:42:01 2017 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;
19   import java.util.concurrent.Callable;
20 + import java.util.concurrent.CancellationException;
21   import java.util.concurrent.CountDownLatch;
22   import java.util.concurrent.ExecutionException;
20 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 29 | import java.util.concurrent.RejectedExec
29   import java.util.concurrent.SynchronousQueue;
30   import java.util.concurrent.ThreadFactory;
31   import java.util.concurrent.ThreadPoolExecutor;
32 < import java.util.concurrent.TimeUnit;
32 > import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
33 > import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
34 > import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
35 > import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
36 > import java.util.concurrent.atomic.AtomicInteger;
37 > import java.util.concurrent.atomic.AtomicReference;
38  
39   import junit.framework.Test;
40   import junit.framework.TestSuite;
# Line 85 | Line 92 | public class ThreadPoolExecutorTest exte
92              new ThreadPoolExecutor(1, 1,
93                                     LONG_DELAY_MS, MILLISECONDS,
94                                     new ArrayBlockingQueue<Runnable>(10));
95 <        final CountDownLatch done = new CountDownLatch(1);
96 <        final Runnable task = new CheckedRunnable() {
97 <            public void realRun() {
98 <                done.countDown();
92 <            }};
93 <        try {
95 >        try (PoolCleaner cleaner = cleaner(p)) {
96 >            final CountDownLatch done = new CountDownLatch(1);
97 >            final Runnable task = new CheckedRunnable() {
98 >                public void realRun() { done.countDown(); }};
99              p.execute(task);
100 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
96 <        } finally {
97 <            joinPool(p);
100 >            await(done);
101          }
102      }
103  
# Line 103 | Line 106 | public class ThreadPoolExecutorTest exte
106       * thread becomes active
107       */
108      public void testGetActiveCount() throws InterruptedException {
109 +        final CountDownLatch done = new CountDownLatch(1);
110          final ThreadPoolExecutor p =
111              new ThreadPoolExecutor(2, 2,
112                                     LONG_DELAY_MS, MILLISECONDS,
113                                     new ArrayBlockingQueue<Runnable>(10));
114 <        final CountDownLatch threadStarted = new CountDownLatch(1);
115 <        final CountDownLatch done = new CountDownLatch(1);
112 <        try {
114 >        try (PoolCleaner cleaner = cleaner(p, done)) {
115 >            final CountDownLatch threadStarted = new CountDownLatch(1);
116              assertEquals(0, p.getActiveCount());
117              p.execute(new CheckedRunnable() {
118                  public void realRun() throws InterruptedException {
119                      threadStarted.countDown();
120                      assertEquals(1, p.getActiveCount());
121 <                    done.await();
121 >                    await(done);
122                  }});
123 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
123 >            await(threadStarted);
124              assertEquals(1, p.getActiveCount());
122        } finally {
123            done.countDown();
124            joinPool(p);
125          }
126      }
127  
# Line 130 | Line 130 | public class ThreadPoolExecutorTest exte
130       */
131      public void testPrestartCoreThread() {
132          final ThreadPoolExecutor p =
133 <            new ThreadPoolExecutor(2, 2,
133 >            new ThreadPoolExecutor(2, 6,
134                                     LONG_DELAY_MS, MILLISECONDS,
135                                     new ArrayBlockingQueue<Runnable>(10));
136 <        assertEquals(0, p.getPoolSize());
137 <        assertTrue(p.prestartCoreThread());
138 <        assertEquals(1, p.getPoolSize());
139 <        assertTrue(p.prestartCoreThread());
140 <        assertEquals(2, p.getPoolSize());
141 <        assertFalse(p.prestartCoreThread());
142 <        assertEquals(2, p.getPoolSize());
143 <        joinPool(p);
136 >        try (PoolCleaner cleaner = cleaner(p)) {
137 >            assertEquals(0, p.getPoolSize());
138 >            assertTrue(p.prestartCoreThread());
139 >            assertEquals(1, p.getPoolSize());
140 >            assertTrue(p.prestartCoreThread());
141 >            assertEquals(2, p.getPoolSize());
142 >            assertFalse(p.prestartCoreThread());
143 >            assertEquals(2, p.getPoolSize());
144 >            p.setCorePoolSize(4);
145 >            assertTrue(p.prestartCoreThread());
146 >            assertEquals(3, p.getPoolSize());
147 >            assertTrue(p.prestartCoreThread());
148 >            assertEquals(4, p.getPoolSize());
149 >            assertFalse(p.prestartCoreThread());
150 >            assertEquals(4, p.getPoolSize());
151 >        }
152      }
153  
154      /**
# Line 148 | Line 156 | public class ThreadPoolExecutorTest exte
156       */
157      public void testPrestartAllCoreThreads() {
158          final ThreadPoolExecutor p =
159 <            new ThreadPoolExecutor(2, 2,
159 >            new ThreadPoolExecutor(2, 6,
160                                     LONG_DELAY_MS, MILLISECONDS,
161                                     new ArrayBlockingQueue<Runnable>(10));
162 <        assertEquals(0, p.getPoolSize());
163 <        p.prestartAllCoreThreads();
164 <        assertEquals(2, p.getPoolSize());
165 <        p.prestartAllCoreThreads();
166 <        assertEquals(2, p.getPoolSize());
167 <        joinPool(p);
162 >        try (PoolCleaner cleaner = cleaner(p)) {
163 >            assertEquals(0, p.getPoolSize());
164 >            p.prestartAllCoreThreads();
165 >            assertEquals(2, p.getPoolSize());
166 >            p.prestartAllCoreThreads();
167 >            assertEquals(2, p.getPoolSize());
168 >            p.setCorePoolSize(4);
169 >            p.prestartAllCoreThreads();
170 >            assertEquals(4, p.getPoolSize());
171 >            p.prestartAllCoreThreads();
172 >            assertEquals(4, p.getPoolSize());
173 >        }
174      }
175  
176      /**
# Line 168 | Line 182 | public class ThreadPoolExecutorTest exte
182              new ThreadPoolExecutor(2, 2,
183                                     LONG_DELAY_MS, MILLISECONDS,
184                                     new ArrayBlockingQueue<Runnable>(10));
185 <        final CountDownLatch threadStarted = new CountDownLatch(1);
186 <        final CountDownLatch threadProceed = new CountDownLatch(1);
187 <        final CountDownLatch threadDone = new CountDownLatch(1);
188 <        try {
185 >        try (PoolCleaner cleaner = cleaner(p)) {
186 >            final CountDownLatch threadStarted = new CountDownLatch(1);
187 >            final CountDownLatch threadProceed = new CountDownLatch(1);
188 >            final CountDownLatch threadDone = new CountDownLatch(1);
189              assertEquals(0, p.getCompletedTaskCount());
190              p.execute(new CheckedRunnable() {
191                  public void realRun() throws InterruptedException {
192                      threadStarted.countDown();
193                      assertEquals(0, p.getCompletedTaskCount());
194 <                    threadProceed.await();
194 >                    await(threadProceed);
195                      threadDone.countDown();
196                  }});
197              await(threadStarted);
198              assertEquals(0, p.getCompletedTaskCount());
199              threadProceed.countDown();
200 <            threadDone.await();
200 >            await(threadDone);
201              long startTime = System.nanoTime();
202              while (p.getCompletedTaskCount() != 1) {
203                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
204                      fail("timed out");
205                  Thread.yield();
206              }
193        } finally {
194            joinPool(p);
207          }
208      }
209  
# Line 203 | Line 215 | public class ThreadPoolExecutorTest exte
215              new ThreadPoolExecutor(1, 1,
216                                     LONG_DELAY_MS, MILLISECONDS,
217                                     new ArrayBlockingQueue<Runnable>(10));
218 <        assertEquals(1, p.getCorePoolSize());
219 <        joinPool(p);
218 >        try (PoolCleaner cleaner = cleaner(p)) {
219 >            assertEquals(1, p.getCorePoolSize());
220 >        }
221      }
222  
223      /**
# Line 215 | Line 228 | public class ThreadPoolExecutorTest exte
228              new ThreadPoolExecutor(2, 2,
229                                     1000, MILLISECONDS,
230                                     new ArrayBlockingQueue<Runnable>(10));
231 <        assertEquals(1, p.getKeepAliveTime(TimeUnit.SECONDS));
232 <        joinPool(p);
231 >        try (PoolCleaner cleaner = cleaner(p)) {
232 >            assertEquals(1, p.getKeepAliveTime(SECONDS));
233 >        }
234      }
235  
236      /**
237       * getThreadFactory returns factory in constructor if not set
238       */
239      public void testGetThreadFactory() {
240 <        ThreadFactory tf = new SimpleThreadFactory();
240 >        ThreadFactory threadFactory = new SimpleThreadFactory();
241          final ThreadPoolExecutor p =
242              new ThreadPoolExecutor(1, 2,
243                                     LONG_DELAY_MS, MILLISECONDS,
244                                     new ArrayBlockingQueue<Runnable>(10),
245 <                                   tf,
245 >                                   threadFactory,
246                                     new NoOpREHandler());
247 <        assertSame(tf, p.getThreadFactory());
248 <        joinPool(p);
247 >        try (PoolCleaner cleaner = cleaner(p)) {
248 >            assertSame(threadFactory, p.getThreadFactory());
249 >        }
250      }
251  
252      /**
# Line 242 | Line 257 | public class ThreadPoolExecutorTest exte
257              new ThreadPoolExecutor(1, 2,
258                                     LONG_DELAY_MS, MILLISECONDS,
259                                     new ArrayBlockingQueue<Runnable>(10));
260 <        ThreadFactory tf = new SimpleThreadFactory();
261 <        p.setThreadFactory(tf);
262 <        assertSame(tf, p.getThreadFactory());
263 <        joinPool(p);
260 >        try (PoolCleaner cleaner = cleaner(p)) {
261 >            ThreadFactory threadFactory = new SimpleThreadFactory();
262 >            p.setThreadFactory(threadFactory);
263 >            assertSame(threadFactory, p.getThreadFactory());
264 >        }
265      }
266  
267      /**
# Line 256 | Line 272 | public class ThreadPoolExecutorTest exte
272              new ThreadPoolExecutor(1, 2,
273                                     LONG_DELAY_MS, MILLISECONDS,
274                                     new ArrayBlockingQueue<Runnable>(10));
275 <        try {
276 <            p.setThreadFactory(null);
277 <            shouldThrow();
278 <        } catch (NullPointerException success) {
279 <        } finally {
280 <            joinPool(p);
275 >        try (PoolCleaner cleaner = cleaner(p)) {
276 >            try {
277 >                p.setThreadFactory(null);
278 >                shouldThrow();
279 >            } catch (NullPointerException success) {}
280 >        }
281 >    }
282 >
283 >    /**
284 >     * The default rejected execution handler is AbortPolicy.
285 >     */
286 >    public void testDefaultRejectedExecutionHandler() {
287 >        final ThreadPoolExecutor p =
288 >            new ThreadPoolExecutor(1, 2,
289 >                                   LONG_DELAY_MS, MILLISECONDS,
290 >                                   new ArrayBlockingQueue<Runnable>(10));
291 >        try (PoolCleaner cleaner = cleaner(p)) {
292 >            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
293          }
294      }
295  
# Line 269 | Line 297 | public class ThreadPoolExecutorTest exte
297       * getRejectedExecutionHandler returns handler in constructor if not set
298       */
299      public void testGetRejectedExecutionHandler() {
300 <        final RejectedExecutionHandler h = new NoOpREHandler();
300 >        final RejectedExecutionHandler handler = new NoOpREHandler();
301          final ThreadPoolExecutor p =
302              new ThreadPoolExecutor(1, 2,
303                                     LONG_DELAY_MS, MILLISECONDS,
304                                     new ArrayBlockingQueue<Runnable>(10),
305 <                                   h);
306 <        assertSame(h, p.getRejectedExecutionHandler());
307 <        joinPool(p);
305 >                                   handler);
306 >        try (PoolCleaner cleaner = cleaner(p)) {
307 >            assertSame(handler, p.getRejectedExecutionHandler());
308 >        }
309      }
310  
311      /**
# Line 288 | Line 317 | public class ThreadPoolExecutorTest exte
317              new ThreadPoolExecutor(1, 2,
318                                     LONG_DELAY_MS, MILLISECONDS,
319                                     new ArrayBlockingQueue<Runnable>(10));
320 <        RejectedExecutionHandler h = new NoOpREHandler();
321 <        p.setRejectedExecutionHandler(h);
322 <        assertSame(h, p.getRejectedExecutionHandler());
323 <        joinPool(p);
320 >        try (PoolCleaner cleaner = cleaner(p)) {
321 >            RejectedExecutionHandler handler = new NoOpREHandler();
322 >            p.setRejectedExecutionHandler(handler);
323 >            assertSame(handler, p.getRejectedExecutionHandler());
324 >        }
325      }
326  
327      /**
# Line 302 | Line 332 | public class ThreadPoolExecutorTest exte
332              new ThreadPoolExecutor(1, 2,
333                                     LONG_DELAY_MS, MILLISECONDS,
334                                     new ArrayBlockingQueue<Runnable>(10));
335 <        try {
336 <            p.setRejectedExecutionHandler(null);
337 <            shouldThrow();
338 <        } catch (NullPointerException success) {
339 <        } finally {
310 <            joinPool(p);
335 >        try (PoolCleaner cleaner = cleaner(p)) {
336 >            try {
337 >                p.setRejectedExecutionHandler(null);
338 >                shouldThrow();
339 >            } catch (NullPointerException success) {}
340          }
341      }
342  
# Line 317 | Line 346 | public class ThreadPoolExecutorTest exte
346       */
347      public void testGetLargestPoolSize() throws InterruptedException {
348          final int THREADS = 3;
349 +        final CountDownLatch done = new CountDownLatch(1);
350          final ThreadPoolExecutor p =
351              new ThreadPoolExecutor(THREADS, THREADS,
352                                     LONG_DELAY_MS, MILLISECONDS,
353                                     new ArrayBlockingQueue<Runnable>(10));
354 <        final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
325 <        final CountDownLatch done = new CountDownLatch(1);
326 <        try {
354 >        try (PoolCleaner cleaner = cleaner(p, done)) {
355              assertEquals(0, p.getLargestPoolSize());
356 +            final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
357              for (int i = 0; i < THREADS; i++)
358                  p.execute(new CheckedRunnable() {
359                      public void realRun() throws InterruptedException {
360                          threadsStarted.countDown();
361 <                        done.await();
361 >                        await(done);
362                          assertEquals(THREADS, p.getLargestPoolSize());
363                      }});
364 <            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
336 <            assertEquals(THREADS, p.getLargestPoolSize());
337 <        } finally {
338 <            done.countDown();
339 <            joinPool(p);
364 >            await(threadsStarted);
365              assertEquals(THREADS, p.getLargestPoolSize());
366          }
367 +        assertEquals(THREADS, p.getLargestPoolSize());
368      }
369  
370      /**
# Line 350 | Line 376 | public class ThreadPoolExecutorTest exte
376              new ThreadPoolExecutor(2, 3,
377                                     LONG_DELAY_MS, MILLISECONDS,
378                                     new ArrayBlockingQueue<Runnable>(10));
379 <        assertEquals(3, p.getMaximumPoolSize());
380 <        joinPool(p);
379 >        try (PoolCleaner cleaner = cleaner(p)) {
380 >            assertEquals(3, p.getMaximumPoolSize());
381 >            p.setMaximumPoolSize(5);
382 >            assertEquals(5, p.getMaximumPoolSize());
383 >            p.setMaximumPoolSize(4);
384 >            assertEquals(4, p.getMaximumPoolSize());
385 >        }
386      }
387  
388      /**
# Line 359 | Line 390 | public class ThreadPoolExecutorTest exte
390       * become active
391       */
392      public void testGetPoolSize() throws InterruptedException {
393 +        final CountDownLatch done = new CountDownLatch(1);
394          final ThreadPoolExecutor p =
395              new ThreadPoolExecutor(1, 1,
396                                     LONG_DELAY_MS, MILLISECONDS,
397                                     new ArrayBlockingQueue<Runnable>(10));
398 <        final CountDownLatch threadStarted = new CountDownLatch(1);
367 <        final CountDownLatch done = new CountDownLatch(1);
368 <        try {
398 >        try (PoolCleaner cleaner = cleaner(p, done)) {
399              assertEquals(0, p.getPoolSize());
400 +            final CountDownLatch threadStarted = new CountDownLatch(1);
401              p.execute(new CheckedRunnable() {
402                  public void realRun() throws InterruptedException {
403                      threadStarted.countDown();
404                      assertEquals(1, p.getPoolSize());
405 <                    done.await();
405 >                    await(done);
406                  }});
407 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
407 >            await(threadStarted);
408              assertEquals(1, p.getPoolSize());
378        } finally {
379            done.countDown();
380            joinPool(p);
409          }
410      }
411  
# Line 385 | Line 413 | public class ThreadPoolExecutorTest exte
413       * getTaskCount increases, but doesn't overestimate, when tasks submitted
414       */
415      public void testGetTaskCount() throws InterruptedException {
416 +        final int TASKS = 3;
417 +        final CountDownLatch done = new CountDownLatch(1);
418          final ThreadPoolExecutor p =
419              new ThreadPoolExecutor(1, 1,
420                                     LONG_DELAY_MS, MILLISECONDS,
421                                     new ArrayBlockingQueue<Runnable>(10));
422 <        final CountDownLatch threadStarted = new CountDownLatch(1);
423 <        final CountDownLatch done = new CountDownLatch(1);
394 <        try {
422 >        try (PoolCleaner cleaner = cleaner(p, done)) {
423 >            final CountDownLatch threadStarted = new CountDownLatch(1);
424              assertEquals(0, p.getTaskCount());
425 +            assertEquals(0, p.getCompletedTaskCount());
426              p.execute(new CheckedRunnable() {
427                  public void realRun() throws InterruptedException {
428                      threadStarted.countDown();
429 <                    assertEquals(1, p.getTaskCount());
400 <                    done.await();
429 >                    await(done);
430                  }});
431 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
431 >            await(threadStarted);
432              assertEquals(1, p.getTaskCount());
433 <        } finally {
434 <            done.countDown();
435 <            joinPool(p);
433 >            assertEquals(0, p.getCompletedTaskCount());
434 >            for (int i = 0; i < TASKS; i++) {
435 >                assertEquals(1 + i, p.getTaskCount());
436 >                p.execute(new CheckedRunnable() {
437 >                    public void realRun() throws InterruptedException {
438 >                        threadStarted.countDown();
439 >                        assertEquals(1 + TASKS, p.getTaskCount());
440 >                        await(done);
441 >                    }});
442 >            }
443 >            assertEquals(1 + TASKS, p.getTaskCount());
444 >            assertEquals(0, p.getCompletedTaskCount());
445          }
446 +        assertEquals(1 + TASKS, p.getTaskCount());
447 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
448      }
449  
450      /**
# Line 415 | Line 455 | public class ThreadPoolExecutorTest exte
455              new ThreadPoolExecutor(1, 1,
456                                     LONG_DELAY_MS, MILLISECONDS,
457                                     new ArrayBlockingQueue<Runnable>(10));
458 <        assertFalse(p.isShutdown());
459 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
460 <        assertTrue(p.isShutdown());
461 <        joinPool(p);
458 >        try (PoolCleaner cleaner = cleaner(p)) {
459 >            assertFalse(p.isShutdown());
460 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
461 >            assertTrue(p.isShutdown());
462 >        }
463      }
464  
465      /**
# Line 429 | Line 470 | public class ThreadPoolExecutorTest exte
470              new ThreadPoolExecutor(1, 1,
471                                     LONG_DELAY_MS, MILLISECONDS,
472                                     new ArrayBlockingQueue<Runnable>(10));
473 <        assertFalse(p.isTerminated());
474 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
475 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
476 <        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
477 <        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
478 <        assertFalse(p.awaitTermination(0L, NANOSECONDS));
479 <        assertFalse(p.awaitTermination(0L, MILLISECONDS));
480 <        long timeoutNanos = 999999L;
481 <        long startTime = System.nanoTime();
482 <        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
483 <        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
484 <        assertFalse(p.isTerminated());
485 <        startTime = System.nanoTime();
486 <        long timeoutMillis = timeoutMillis();
487 <        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
488 <        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
489 <        assertFalse(p.isTerminated());
490 <        p.shutdown();
491 <        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
492 <        assertTrue(p.isTerminated());
473 >        try (PoolCleaner cleaner = cleaner(p)) {
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(randomExpiredTimeout(),
480 >                                           randomTimeUnit()));
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 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
492 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
493 >            assertTrue(p.isTerminated());
494 >        }
495      }
496  
497      /**
# Line 459 | Line 502 | public class ThreadPoolExecutorTest exte
502              new ThreadPoolExecutor(1, 1,
503                                     LONG_DELAY_MS, MILLISECONDS,
504                                     new ArrayBlockingQueue<Runnable>(10));
505 <        final CountDownLatch threadStarted = new CountDownLatch(1);
506 <        final CountDownLatch done = new CountDownLatch(1);
507 <        assertFalse(p.isTerminated());
508 <        try {
505 >        try (PoolCleaner cleaner = cleaner(p)) {
506 >            final CountDownLatch threadStarted = new CountDownLatch(1);
507 >            final CountDownLatch done = new CountDownLatch(1);
508 >            assertFalse(p.isTerminating());
509              p.execute(new CheckedRunnable() {
510                  public void realRun() throws InterruptedException {
511 <                    assertFalse(p.isTerminated());
511 >                    assertFalse(p.isTerminating());
512                      threadStarted.countDown();
513 <                    done.await();
513 >                    await(done);
514                  }});
515 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
515 >            await(threadStarted);
516              assertFalse(p.isTerminating());
517              done.countDown();
475        } finally {
518              try { p.shutdown(); } catch (SecurityException ok) { return; }
519 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
520 +            assertTrue(p.isTerminated());
521 +            assertFalse(p.isTerminating());
522          }
478        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
479        assertTrue(p.isTerminated());
523      }
524  
525      /**
# Line 487 | Line 530 | public class ThreadPoolExecutorTest exte
530              new ThreadPoolExecutor(1, 1,
531                                     LONG_DELAY_MS, MILLISECONDS,
532                                     new ArrayBlockingQueue<Runnable>(10));
533 <        final CountDownLatch threadStarted = new CountDownLatch(1);
534 <        final CountDownLatch done = new CountDownLatch(1);
535 <        try {
533 >        try (PoolCleaner cleaner = cleaner(p)) {
534 >            final CountDownLatch threadStarted = new CountDownLatch(1);
535 >            final CountDownLatch done = new CountDownLatch(1);
536              assertFalse(p.isTerminating());
537              p.execute(new CheckedRunnable() {
538                  public void realRun() throws InterruptedException {
539                      assertFalse(p.isTerminating());
540                      threadStarted.countDown();
541 <                    done.await();
541 >                    await(done);
542                  }});
543 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
543 >            await(threadStarted);
544              assertFalse(p.isTerminating());
545              done.countDown();
503        } finally {
546              try { p.shutdown(); } catch (SecurityException ok) { return; }
547 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
548 +            assertTrue(p.isTerminated());
549 +            assertFalse(p.isTerminating());
550          }
506        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
507        assertTrue(p.isTerminated());
508        assertFalse(p.isTerminating());
551      }
552  
553      /**
554       * getQueue returns the work queue, which contains queued tasks
555       */
556      public void testGetQueue() throws InterruptedException {
557 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
557 >        final CountDownLatch done = new CountDownLatch(1);
558 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
559          final ThreadPoolExecutor p =
560              new ThreadPoolExecutor(1, 1,
561                                     LONG_DELAY_MS, MILLISECONDS,
562                                     q);
563 <        final CountDownLatch threadStarted = new CountDownLatch(1);
564 <        final CountDownLatch done = new CountDownLatch(1);
522 <        try {
563 >        try (PoolCleaner cleaner = cleaner(p, done)) {
564 >            final CountDownLatch threadStarted = new CountDownLatch(1);
565              FutureTask[] tasks = new FutureTask[5];
566              for (int i = 0; i < tasks.length; i++) {
567                  Callable task = new CheckedCallable<Boolean>() {
568                      public Boolean realCall() throws InterruptedException {
569                          threadStarted.countDown();
570                          assertSame(q, p.getQueue());
571 <                        done.await();
571 >                        await(done);
572                          return Boolean.TRUE;
573                      }};
574                  tasks[i] = new FutureTask(task);
575                  p.execute(tasks[i]);
576              }
577 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
577 >            await(threadStarted);
578              assertSame(q, p.getQueue());
579              assertFalse(q.contains(tasks[0]));
580              assertTrue(q.contains(tasks[tasks.length - 1]));
581              assertEquals(tasks.length - 1, q.size());
540        } finally {
541            done.countDown();
542            joinPool(p);
582          }
583      }
584  
# Line 547 | Line 586 | public class ThreadPoolExecutorTest exte
586       * remove(task) removes queued task, and fails to remove active task
587       */
588      public void testRemove() throws InterruptedException {
589 <        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
589 >        final CountDownLatch done = new CountDownLatch(1);
590 >        BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
591          final ThreadPoolExecutor p =
592              new ThreadPoolExecutor(1, 1,
593                                     LONG_DELAY_MS, MILLISECONDS,
594                                     q);
595 <        Runnable[] tasks = new Runnable[5];
596 <        final CountDownLatch threadStarted = new CountDownLatch(1);
597 <        final CountDownLatch done = new CountDownLatch(1);
558 <        try {
595 >        try (PoolCleaner cleaner = cleaner(p, done)) {
596 >            Runnable[] tasks = new Runnable[6];
597 >            final CountDownLatch threadStarted = new CountDownLatch(1);
598              for (int i = 0; i < tasks.length; i++) {
599                  tasks[i] = new CheckedRunnable() {
600                      public void realRun() throws InterruptedException {
601                          threadStarted.countDown();
602 <                        done.await();
602 >                        await(done);
603                      }};
604                  p.execute(tasks[i]);
605              }
606 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
606 >            await(threadStarted);
607              assertFalse(p.remove(tasks[0]));
608              assertTrue(q.contains(tasks[4]));
609              assertTrue(q.contains(tasks[3]));
# Line 574 | Line 613 | public class ThreadPoolExecutorTest exte
613              assertTrue(q.contains(tasks[3]));
614              assertTrue(p.remove(tasks[3]));
615              assertFalse(q.contains(tasks[3]));
577        } finally {
578            done.countDown();
579            joinPool(p);
616          }
617      }
618  
# Line 586 | Line 622 | public class ThreadPoolExecutorTest exte
622      public void testPurge() throws InterruptedException {
623          final CountDownLatch threadStarted = new CountDownLatch(1);
624          final CountDownLatch done = new CountDownLatch(1);
625 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
625 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
626          final ThreadPoolExecutor p =
627              new ThreadPoolExecutor(1, 1,
628                                     LONG_DELAY_MS, MILLISECONDS,
629                                     q);
630 <        FutureTask[] tasks = new FutureTask[5];
631 <        try {
630 >        try (PoolCleaner cleaner = cleaner(p, done)) {
631 >            FutureTask[] tasks = new FutureTask[5];
632              for (int i = 0; i < tasks.length; i++) {
633                  Callable task = new CheckedCallable<Boolean>() {
634                      public Boolean realCall() throws InterruptedException {
635                          threadStarted.countDown();
636 <                        done.await();
636 >                        await(done);
637                          return Boolean.TRUE;
638                      }};
639                  tasks[i] = new FutureTask(task);
640                  p.execute(tasks[i]);
641              }
642 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
642 >            await(threadStarted);
643              assertEquals(tasks.length, p.getTaskCount());
644              assertEquals(tasks.length - 1, q.size());
645              assertEquals(1L, p.getActiveCount());
# Line 616 | Line 652 | public class ThreadPoolExecutorTest exte
652              p.purge();         // Nothing to do
653              assertEquals(tasks.length - 3, q.size());
654              assertEquals(tasks.length - 2, p.getTaskCount());
619        } finally {
620            done.countDown();
621            joinPool(p);
655          }
656      }
657  
658      /**
659 <     * shutdownNow returns a list containing tasks that were not run
659 >     * shutdownNow returns a list containing tasks that were not run,
660 >     * and those tasks are drained from the queue
661       */
662 <    public void testShutdownNow() {
662 >    public void testShutdownNow() throws InterruptedException {
663 >        final int poolSize = 2;
664 >        final int count = 5;
665 >        final AtomicInteger ran = new AtomicInteger(0);
666          final ThreadPoolExecutor p =
667 <            new ThreadPoolExecutor(1, 1,
667 >            new ThreadPoolExecutor(poolSize, poolSize,
668                                     LONG_DELAY_MS, MILLISECONDS,
669                                     new ArrayBlockingQueue<Runnable>(10));
670 <        List l;
671 <        try {
672 <            for (int i = 0; i < 5; i++)
636 <                p.execute(new MediumPossiblyInterruptedRunnable());
637 <        }
638 <        finally {
670 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
671 >        Runnable waiter = new CheckedRunnable() { public void realRun() {
672 >            threadsStarted.countDown();
673              try {
674 <                l = p.shutdownNow();
675 <            } catch (SecurityException ok) { return; }
674 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
675 >            } catch (InterruptedException success) {}
676 >            ran.getAndIncrement();
677 >        }};
678 >        for (int i = 0; i < count; i++)
679 >            p.execute(waiter);
680 >        await(threadsStarted);
681 >        assertEquals(poolSize, p.getActiveCount());
682 >        assertEquals(0, p.getCompletedTaskCount());
683 >        final List<Runnable> queuedTasks;
684 >        try {
685 >            queuedTasks = p.shutdownNow();
686 >        } catch (SecurityException ok) {
687 >            return; // Allowed in case test doesn't have privs
688          }
689          assertTrue(p.isShutdown());
690 <        assertTrue(l.size() <= 4);
690 >        assertTrue(p.getQueue().isEmpty());
691 >        assertEquals(count - poolSize, queuedTasks.size());
692 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
693 >        assertTrue(p.isTerminated());
694 >        assertEquals(poolSize, ran.get());
695 >        assertEquals(poolSize, p.getCompletedTaskCount());
696      }
697  
698      // Exception Tests
# Line 988 | Line 1039 | public class ThreadPoolExecutorTest exte
1039       * get of submitted callable throws InterruptedException if interrupted
1040       */
1041      public void testInterruptedSubmit() throws InterruptedException {
1042 +        final CountDownLatch done = new CountDownLatch(1);
1043          final ThreadPoolExecutor p =
1044              new ThreadPoolExecutor(1, 1,
1045 <                                   60, TimeUnit.SECONDS,
1045 >                                   60, SECONDS,
1046                                     new ArrayBlockingQueue<Runnable>(10));
1047  
1048 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1049 <        final CountDownLatch done = new CountDownLatch(1);
998 <        try {
1048 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1049 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1050              Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1051                  public void realRun() throws Exception {
1052                      Callable task = new CheckedCallable<Boolean>() {
1053                          public Boolean realCall() throws InterruptedException {
1054                              threadStarted.countDown();
1055 <                            done.await();
1055 >                            await(done);
1056                              return Boolean.TRUE;
1057                          }};
1058                      p.submit(task).get();
1059                  }});
1060  
1061 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
1061 >            await(threadStarted);
1062              t.interrupt();
1063 <            awaitTermination(t, MEDIUM_DELAY_MS);
1013 <        } finally {
1014 <            done.countDown();
1015 <            joinPool(p);
1063 >            awaitTermination(t);
1064          }
1065      }
1066  
# Line 1020 | Line 1068 | public class ThreadPoolExecutorTest exte
1068       * execute throws RejectedExecutionException if saturated.
1069       */
1070      public void testSaturatedExecute() {
1071 <        ThreadPoolExecutor p =
1071 >        final CountDownLatch done = new CountDownLatch(1);
1072 >        final ThreadPoolExecutor p =
1073              new ThreadPoolExecutor(1, 1,
1074                                     LONG_DELAY_MS, MILLISECONDS,
1075                                     new ArrayBlockingQueue<Runnable>(1));
1076 <        final CountDownLatch done = new CountDownLatch(1);
1028 <        try {
1076 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1077              Runnable task = new CheckedRunnable() {
1078                  public void realRun() throws InterruptedException {
1079 <                    done.await();
1079 >                    await(done);
1080                  }};
1081              for (int i = 0; i < 2; ++i)
1082                  p.execute(task);
# Line 1039 | Line 1087 | public class ThreadPoolExecutorTest exte
1087                  } catch (RejectedExecutionException success) {}
1088                  assertTrue(p.getTaskCount() <= 2);
1089              }
1042        } finally {
1043            done.countDown();
1044            joinPool(p);
1090          }
1091      }
1092  
# Line 1049 | Line 1094 | public class ThreadPoolExecutorTest exte
1094       * submit(runnable) throws RejectedExecutionException if saturated.
1095       */
1096      public void testSaturatedSubmitRunnable() {
1097 <        ThreadPoolExecutor p =
1097 >        final CountDownLatch done = new CountDownLatch(1);
1098 >        final ThreadPoolExecutor p =
1099              new ThreadPoolExecutor(1, 1,
1100                                     LONG_DELAY_MS, MILLISECONDS,
1101                                     new ArrayBlockingQueue<Runnable>(1));
1102 <        final CountDownLatch done = new CountDownLatch(1);
1057 <        try {
1102 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1103              Runnable task = new CheckedRunnable() {
1104                  public void realRun() throws InterruptedException {
1105 <                    done.await();
1105 >                    await(done);
1106                  }};
1107              for (int i = 0; i < 2; ++i)
1108                  p.submit(task);
# Line 1068 | Line 1113 | public class ThreadPoolExecutorTest exte
1113                  } catch (RejectedExecutionException success) {}
1114                  assertTrue(p.getTaskCount() <= 2);
1115              }
1071        } finally {
1072            done.countDown();
1073            joinPool(p);
1116          }
1117      }
1118  
# Line 1078 | Line 1120 | public class ThreadPoolExecutorTest exte
1120       * submit(callable) throws RejectedExecutionException if saturated.
1121       */
1122      public void testSaturatedSubmitCallable() {
1123 <        ThreadPoolExecutor p =
1123 >        final CountDownLatch done = new CountDownLatch(1);
1124 >        final ThreadPoolExecutor p =
1125              new ThreadPoolExecutor(1, 1,
1126                                     LONG_DELAY_MS, MILLISECONDS,
1127                                     new ArrayBlockingQueue<Runnable>(1));
1128 <        final CountDownLatch done = new CountDownLatch(1);
1086 <        try {
1128 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1129              Runnable task = new CheckedRunnable() {
1130                  public void realRun() throws InterruptedException {
1131 <                    done.await();
1131 >                    await(done);
1132                  }};
1133              for (int i = 0; i < 2; ++i)
1134 <                p.submit(Executors.callable(task));
1134 >                p.execute(task);
1135              for (int i = 0; i < 2; ++i) {
1136                  try {
1137                      p.execute(task);
# Line 1097 | Line 1139 | public class ThreadPoolExecutorTest exte
1139                  } catch (RejectedExecutionException success) {}
1140                  assertTrue(p.getTaskCount() <= 2);
1141              }
1100        } finally {
1101            done.countDown();
1102            joinPool(p);
1142          }
1143      }
1144  
# Line 1107 | Line 1146 | public class ThreadPoolExecutorTest exte
1146       * executor using CallerRunsPolicy runs task if saturated.
1147       */
1148      public void testSaturatedExecute2() {
1110        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1149          final ThreadPoolExecutor p =
1150              new ThreadPoolExecutor(1, 1,
1151                                     LONG_DELAY_MS,
1152                                     MILLISECONDS,
1153                                     new ArrayBlockingQueue<Runnable>(1),
1154 <                                   h);
1155 <        try {
1154 >                                   new CallerRunsPolicy());
1155 >        try (PoolCleaner cleaner = cleaner(p)) {
1156 >            final CountDownLatch done = new CountDownLatch(1);
1157 >            Runnable blocker = new CheckedRunnable() {
1158 >                public void realRun() throws InterruptedException {
1159 >                    await(done);
1160 >                }};
1161 >            p.execute(blocker);
1162              TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1163 <            for (int i = 0; i < tasks.length; ++i)
1163 >            for (int i = 0; i < tasks.length; i++)
1164                  tasks[i] = new TrackedNoOpRunnable();
1165 <            TrackedLongRunnable mr = new TrackedLongRunnable();
1122 <            p.execute(mr);
1123 <            for (int i = 0; i < tasks.length; ++i)
1165 >            for (int i = 0; i < tasks.length; i++)
1166                  p.execute(tasks[i]);
1167 <            for (int i = 1; i < tasks.length; ++i)
1167 >            for (int i = 1; i < tasks.length; i++)
1168                  assertTrue(tasks[i].done);
1169 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1170 <        } finally {
1129 <            joinPool(p);
1169 >            assertFalse(tasks[0].done); // waiting in queue
1170 >            done.countDown();
1171          }
1172      }
1173  
# Line 1134 | Line 1175 | public class ThreadPoolExecutorTest exte
1175       * executor using DiscardPolicy drops task if saturated.
1176       */
1177      public void testSaturatedExecute3() {
1178 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1178 >        final CountDownLatch done = new CountDownLatch(1);
1179 >        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1180 >        for (int i = 0; i < tasks.length; ++i)
1181 >            tasks[i] = new TrackedNoOpRunnable();
1182          final ThreadPoolExecutor p =
1183              new ThreadPoolExecutor(1, 1,
1184 <                                   LONG_DELAY_MS, MILLISECONDS,
1185 <                                   new ArrayBlockingQueue<Runnable>(1),
1186 <                                   h);
1187 <        try {
1188 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1189 <            for (int i = 0; i < tasks.length; ++i)
1146 <                tasks[i] = new TrackedNoOpRunnable();
1147 <            p.execute(new TrackedLongRunnable());
1184 >                          LONG_DELAY_MS, MILLISECONDS,
1185 >                          new ArrayBlockingQueue<Runnable>(1),
1186 >                          new DiscardPolicy());
1187 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1188 >            p.execute(awaiter(done));
1189 >
1190              for (TrackedNoOpRunnable task : tasks)
1191                  p.execute(task);
1192 <            for (TrackedNoOpRunnable task : tasks)
1193 <                assertFalse(task.done);
1152 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1153 <        } finally {
1154 <            joinPool(p);
1192 >            for (int i = 1; i < tasks.length; i++)
1193 >                assertFalse(tasks[i].done);
1194          }
1195 +        for (int i = 1; i < tasks.length; i++)
1196 +            assertFalse(tasks[i].done);
1197 +        assertTrue(tasks[0].done); // was waiting in queue
1198      }
1199  
1200      /**
1201       * executor using DiscardOldestPolicy drops oldest task if saturated.
1202       */
1203      public void testSaturatedExecute4() {
1204 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1204 >        final CountDownLatch done = new CountDownLatch(1);
1205 >        LatchAwaiter r1 = awaiter(done);
1206 >        LatchAwaiter r2 = awaiter(done);
1207 >        LatchAwaiter r3 = awaiter(done);
1208          final ThreadPoolExecutor p =
1209              new ThreadPoolExecutor(1, 1,
1210                                     LONG_DELAY_MS, MILLISECONDS,
1211                                     new ArrayBlockingQueue<Runnable>(1),
1212 <                                   h);
1213 <        try {
1214 <            p.execute(new TrackedLongRunnable());
1215 <            TrackedLongRunnable r2 = new TrackedLongRunnable();
1212 >                                   new DiscardOldestPolicy());
1213 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1214 >            assertEquals(LatchAwaiter.NEW, r1.state);
1215 >            assertEquals(LatchAwaiter.NEW, r2.state);
1216 >            assertEquals(LatchAwaiter.NEW, r3.state);
1217 >            p.execute(r1);
1218              p.execute(r2);
1219              assertTrue(p.getQueue().contains(r2));
1173            TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1220              p.execute(r3);
1221              assertFalse(p.getQueue().contains(r2));
1222              assertTrue(p.getQueue().contains(r3));
1177            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1178        } finally {
1179            joinPool(p);
1223          }
1224 +        assertEquals(LatchAwaiter.DONE, r1.state);
1225 +        assertEquals(LatchAwaiter.NEW, r2.state);
1226 +        assertEquals(LatchAwaiter.DONE, r3.state);
1227      }
1228  
1229      /**
1230       * execute throws RejectedExecutionException if shutdown
1231       */
1232      public void testRejectedExecutionExceptionOnShutdown() {
1233 <        ThreadPoolExecutor p =
1233 >        final ThreadPoolExecutor p =
1234              new ThreadPoolExecutor(1, 1,
1235                                     LONG_DELAY_MS, MILLISECONDS,
1236                                     new ArrayBlockingQueue<Runnable>(1));
1237          try { p.shutdown(); } catch (SecurityException ok) { return; }
1238 <        try {
1239 <            p.execute(new NoOpRunnable());
1240 <            shouldThrow();
1241 <        } catch (RejectedExecutionException success) {}
1242 <
1243 <        joinPool(p);
1238 >        try (PoolCleaner cleaner = cleaner(p)) {
1239 >            try {
1240 >                p.execute(new NoOpRunnable());
1241 >                shouldThrow();
1242 >            } catch (RejectedExecutionException success) {}
1243 >        }
1244      }
1245  
1246      /**
1247       * execute using CallerRunsPolicy drops task on shutdown
1248       */
1249      public void testCallerRunsOnShutdown() {
1250 <        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1250 >        RejectedExecutionHandler h = new CallerRunsPolicy();
1251          final ThreadPoolExecutor p =
1252              new ThreadPoolExecutor(1, 1,
1253                                     LONG_DELAY_MS, MILLISECONDS,
1254                                     new ArrayBlockingQueue<Runnable>(1), h);
1255  
1256          try { p.shutdown(); } catch (SecurityException ok) { return; }
1257 <        try {
1257 >        try (PoolCleaner cleaner = cleaner(p)) {
1258              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1259              p.execute(r);
1260              assertFalse(r.done);
1215        } finally {
1216            joinPool(p);
1261          }
1262      }
1263  
# Line 1221 | Line 1265 | public class ThreadPoolExecutorTest exte
1265       * execute using DiscardPolicy drops task on shutdown
1266       */
1267      public void testDiscardOnShutdown() {
1268 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1225 <        ThreadPoolExecutor p =
1268 >        final ThreadPoolExecutor p =
1269              new ThreadPoolExecutor(1, 1,
1270                                     LONG_DELAY_MS, MILLISECONDS,
1271                                     new ArrayBlockingQueue<Runnable>(1),
1272 <                                   h);
1272 >                                   new DiscardPolicy());
1273  
1274          try { p.shutdown(); } catch (SecurityException ok) { return; }
1275 <        try {
1275 >        try (PoolCleaner cleaner = cleaner(p)) {
1276              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1277              p.execute(r);
1278              assertFalse(r.done);
1236        } finally {
1237            joinPool(p);
1279          }
1280      }
1281  
# Line 1242 | Line 1283 | public class ThreadPoolExecutorTest exte
1283       * execute using DiscardOldestPolicy drops task on shutdown
1284       */
1285      public void testDiscardOldestOnShutdown() {
1286 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1246 <        ThreadPoolExecutor p =
1286 >        final ThreadPoolExecutor p =
1287              new ThreadPoolExecutor(1, 1,
1288                                     LONG_DELAY_MS, MILLISECONDS,
1289                                     new ArrayBlockingQueue<Runnable>(1),
1290 <                                   h);
1290 >                                   new DiscardOldestPolicy());
1291  
1292          try { p.shutdown(); } catch (SecurityException ok) { return; }
1293 <        try {
1293 >        try (PoolCleaner cleaner = cleaner(p)) {
1294              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1295              p.execute(r);
1296              assertFalse(r.done);
1257        } finally {
1258            joinPool(p);
1297          }
1298      }
1299  
# Line 1263 | Line 1301 | public class ThreadPoolExecutorTest exte
1301       * execute(null) throws NPE
1302       */
1303      public void testExecuteNull() {
1304 <        ThreadPoolExecutor p =
1304 >        final ThreadPoolExecutor p =
1305              new ThreadPoolExecutor(1, 2,
1306 <                                   LONG_DELAY_MS, MILLISECONDS,
1306 >                                   1L, SECONDS,
1307                                     new ArrayBlockingQueue<Runnable>(10));
1308 <        try {
1309 <            p.execute(null);
1310 <            shouldThrow();
1311 <        } catch (NullPointerException success) {}
1312 <
1313 <        joinPool(p);
1308 >        try (PoolCleaner cleaner = cleaner(p)) {
1309 >            try {
1310 >                p.execute(null);
1311 >                shouldThrow();
1312 >            } catch (NullPointerException success) {}
1313 >        }
1314      }
1315  
1316      /**
1317       * setCorePoolSize of negative value throws IllegalArgumentException
1318       */
1319      public void testCorePoolSizeIllegalArgumentException() {
1320 <        ThreadPoolExecutor p =
1320 >        final ThreadPoolExecutor p =
1321              new ThreadPoolExecutor(1, 2,
1322                                     LONG_DELAY_MS, MILLISECONDS,
1323                                     new ArrayBlockingQueue<Runnable>(10));
1324 <        try {
1325 <            p.setCorePoolSize(-1);
1326 <            shouldThrow();
1327 <        } catch (IllegalArgumentException success) {
1328 <        } finally {
1291 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1324 >        try (PoolCleaner cleaner = cleaner(p)) {
1325 >            try {
1326 >                p.setCorePoolSize(-1);
1327 >                shouldThrow();
1328 >            } catch (IllegalArgumentException success) {}
1329          }
1293        joinPool(p);
1330      }
1331  
1332      /**
# Line 1298 | Line 1334 | public class ThreadPoolExecutorTest exte
1334       * given a value less the core pool size
1335       */
1336      public void testMaximumPoolSizeIllegalArgumentException() {
1337 <        ThreadPoolExecutor p =
1337 >        final ThreadPoolExecutor p =
1338              new ThreadPoolExecutor(2, 3,
1339                                     LONG_DELAY_MS, MILLISECONDS,
1340                                     new ArrayBlockingQueue<Runnable>(10));
1341 <        try {
1342 <            p.setMaximumPoolSize(1);
1343 <            shouldThrow();
1344 <        } catch (IllegalArgumentException success) {
1345 <        } finally {
1310 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1341 >        try (PoolCleaner cleaner = cleaner(p)) {
1342 >            try {
1343 >                p.setMaximumPoolSize(1);
1344 >                shouldThrow();
1345 >            } catch (IllegalArgumentException success) {}
1346          }
1312        joinPool(p);
1347      }
1348  
1349      /**
# Line 1317 | Line 1351 | public class ThreadPoolExecutorTest exte
1351       * if given a negative value
1352       */
1353      public void testMaximumPoolSizeIllegalArgumentException2() {
1354 <        ThreadPoolExecutor p =
1354 >        final ThreadPoolExecutor p =
1355              new ThreadPoolExecutor(2, 3,
1356                                     LONG_DELAY_MS, MILLISECONDS,
1357                                     new ArrayBlockingQueue<Runnable>(10));
1358 <        try {
1359 <            p.setMaximumPoolSize(-1);
1360 <            shouldThrow();
1361 <        } catch (IllegalArgumentException success) {
1362 <        } finally {
1363 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1358 >        try (PoolCleaner cleaner = cleaner(p)) {
1359 >            try {
1360 >                p.setMaximumPoolSize(-1);
1361 >                shouldThrow();
1362 >            } catch (IllegalArgumentException success) {}
1363 >        }
1364 >    }
1365 >
1366 >    /**
1367 >     * Configuration changes that allow core pool size greater than
1368 >     * max pool size result in IllegalArgumentException.
1369 >     */
1370 >    public void testPoolSizeInvariants() {
1371 >        final ThreadPoolExecutor p =
1372 >            new ThreadPoolExecutor(1, 1,
1373 >                                   LONG_DELAY_MS, MILLISECONDS,
1374 >                                   new ArrayBlockingQueue<Runnable>(10));
1375 >        try (PoolCleaner cleaner = cleaner(p)) {
1376 >            for (int s = 1; s < 5; s++) {
1377 >                p.setMaximumPoolSize(s);
1378 >                p.setCorePoolSize(s);
1379 >                try {
1380 >                    p.setMaximumPoolSize(s - 1);
1381 >                    shouldThrow();
1382 >                } catch (IllegalArgumentException success) {}
1383 >                assertEquals(s, p.getCorePoolSize());
1384 >                assertEquals(s, p.getMaximumPoolSize());
1385 >                try {
1386 >                    p.setCorePoolSize(s + 1);
1387 >                    shouldThrow();
1388 >                } catch (IllegalArgumentException success) {}
1389 >                assertEquals(s, p.getCorePoolSize());
1390 >                assertEquals(s, p.getMaximumPoolSize());
1391 >            }
1392          }
1331        joinPool(p);
1393      }
1394  
1395      /**
# Line 1336 | Line 1397 | public class ThreadPoolExecutorTest exte
1397       * when given a negative value
1398       */
1399      public void testKeepAliveTimeIllegalArgumentException() {
1400 <        ThreadPoolExecutor p =
1400 >        final ThreadPoolExecutor p =
1401              new ThreadPoolExecutor(2, 3,
1402                                     LONG_DELAY_MS, MILLISECONDS,
1403                                     new ArrayBlockingQueue<Runnable>(10));
1404 <        try {
1405 <            p.setKeepAliveTime(-1,MILLISECONDS);
1406 <            shouldThrow();
1407 <        } catch (IllegalArgumentException success) {
1408 <        } finally {
1348 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1404 >        try (PoolCleaner cleaner = cleaner(p)) {
1405 >            try {
1406 >                p.setKeepAliveTime(-1, MILLISECONDS);
1407 >                shouldThrow();
1408 >            } catch (IllegalArgumentException success) {}
1409          }
1350        joinPool(p);
1410      }
1411  
1412      /**
# Line 1355 | Line 1414 | public class ThreadPoolExecutorTest exte
1414       */
1415      public void testTerminated() {
1416          ExtendedTPE p = new ExtendedTPE();
1417 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
1418 <        assertTrue(p.terminatedCalled());
1419 <        joinPool(p);
1417 >        try (PoolCleaner cleaner = cleaner(p)) {
1418 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
1419 >            assertTrue(p.terminatedCalled());
1420 >            assertTrue(p.isShutdown());
1421 >        }
1422      }
1423  
1424      /**
# Line 1365 | Line 1426 | public class ThreadPoolExecutorTest exte
1426       */
1427      public void testBeforeAfter() throws InterruptedException {
1428          ExtendedTPE p = new ExtendedTPE();
1429 <        try {
1429 >        try (PoolCleaner cleaner = cleaner(p)) {
1430              final CountDownLatch done = new CountDownLatch(1);
1431              p.execute(new CheckedRunnable() {
1432                  public void realRun() {
# Line 1375 | Line 1436 | public class ThreadPoolExecutorTest exte
1436              assertEquals(0, done.getCount());
1437              assertTrue(p.afterCalled());
1438              assertTrue(p.beforeCalled());
1378            try { p.shutdown(); } catch (SecurityException ok) { return; }
1379        } finally {
1380            joinPool(p);
1439          }
1440      }
1441  
# Line 1385 | Line 1443 | public class ThreadPoolExecutorTest exte
1443       * completed submit of callable returns result
1444       */
1445      public void testSubmitCallable() throws Exception {
1446 <        ExecutorService e =
1446 >        final ExecutorService e =
1447              new ThreadPoolExecutor(2, 2,
1448                                     LONG_DELAY_MS, MILLISECONDS,
1449                                     new ArrayBlockingQueue<Runnable>(10));
1450 <        try {
1450 >        try (PoolCleaner cleaner = cleaner(e)) {
1451              Future<String> future = e.submit(new StringTask());
1452              String result = future.get();
1453              assertSame(TEST_STRING, result);
1396        } finally {
1397            joinPool(e);
1454          }
1455      }
1456  
# Line 1402 | Line 1458 | public class ThreadPoolExecutorTest exte
1458       * completed submit of runnable returns successfully
1459       */
1460      public void testSubmitRunnable() throws Exception {
1461 <        ExecutorService e =
1461 >        final ExecutorService e =
1462              new ThreadPoolExecutor(2, 2,
1463                                     LONG_DELAY_MS, MILLISECONDS,
1464                                     new ArrayBlockingQueue<Runnable>(10));
1465 <        try {
1465 >        try (PoolCleaner cleaner = cleaner(e)) {
1466              Future<?> future = e.submit(new NoOpRunnable());
1467              future.get();
1468              assertTrue(future.isDone());
1413        } finally {
1414            joinPool(e);
1469          }
1470      }
1471  
# Line 1419 | Line 1473 | public class ThreadPoolExecutorTest exte
1473       * completed submit of (runnable, result) returns result
1474       */
1475      public void testSubmitRunnable2() throws Exception {
1476 <        ExecutorService e =
1476 >        final ExecutorService e =
1477              new ThreadPoolExecutor(2, 2,
1478                                     LONG_DELAY_MS, MILLISECONDS,
1479                                     new ArrayBlockingQueue<Runnable>(10));
1480 <        try {
1480 >        try (PoolCleaner cleaner = cleaner(e)) {
1481              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1482              String result = future.get();
1483              assertSame(TEST_STRING, result);
1430        } finally {
1431            joinPool(e);
1484          }
1485      }
1486  
# Line 1436 | Line 1488 | public class ThreadPoolExecutorTest exte
1488       * invokeAny(null) throws NPE
1489       */
1490      public void testInvokeAny1() throws Exception {
1491 <        ExecutorService e =
1491 >        final ExecutorService e =
1492              new ThreadPoolExecutor(2, 2,
1493                                     LONG_DELAY_MS, MILLISECONDS,
1494                                     new ArrayBlockingQueue<Runnable>(10));
1495 <        try {
1496 <            e.invokeAny(null);
1497 <            shouldThrow();
1498 <        } catch (NullPointerException success) {
1499 <        } finally {
1448 <            joinPool(e);
1495 >        try (PoolCleaner cleaner = cleaner(e)) {
1496 >            try {
1497 >                e.invokeAny(null);
1498 >                shouldThrow();
1499 >            } catch (NullPointerException success) {}
1500          }
1501      }
1502  
1503      /**
1504 <     * invokeAny(empty collection) throws IAE
1504 >     * invokeAny(empty collection) throws IllegalArgumentException
1505       */
1506      public void testInvokeAny2() throws Exception {
1507 <        ExecutorService e =
1507 >        final ExecutorService e =
1508              new ThreadPoolExecutor(2, 2,
1509                                     LONG_DELAY_MS, MILLISECONDS,
1510                                     new ArrayBlockingQueue<Runnable>(10));
1511 <        try {
1512 <            e.invokeAny(new ArrayList<Callable<String>>());
1513 <            shouldThrow();
1514 <        } catch (IllegalArgumentException success) {
1515 <        } finally {
1465 <            joinPool(e);
1511 >        try (PoolCleaner cleaner = cleaner(e)) {
1512 >            try {
1513 >                e.invokeAny(new ArrayList<Callable<String>>());
1514 >                shouldThrow();
1515 >            } catch (IllegalArgumentException success) {}
1516          }
1517      }
1518  
# Line 1475 | Line 1525 | public class ThreadPoolExecutorTest exte
1525              new ThreadPoolExecutor(2, 2,
1526                                     LONG_DELAY_MS, MILLISECONDS,
1527                                     new ArrayBlockingQueue<Runnable>(10));
1528 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1529 <        l.add(latchAwaitingStringTask(latch));
1530 <        l.add(null);
1531 <        try {
1532 <            e.invokeAny(l);
1533 <            shouldThrow();
1534 <        } catch (NullPointerException success) {
1535 <        } finally {
1528 >        try (PoolCleaner cleaner = cleaner(e)) {
1529 >            List<Callable<String>> l = new ArrayList<>();
1530 >            l.add(latchAwaitingStringTask(latch));
1531 >            l.add(null);
1532 >            try {
1533 >                e.invokeAny(l);
1534 >                shouldThrow();
1535 >            } catch (NullPointerException success) {}
1536              latch.countDown();
1487            joinPool(e);
1537          }
1538      }
1539  
# Line 1492 | Line 1541 | public class ThreadPoolExecutorTest exte
1541       * invokeAny(c) throws ExecutionException if no task completes
1542       */
1543      public void testInvokeAny4() throws Exception {
1544 <        ExecutorService e =
1544 >        final ExecutorService e =
1545              new ThreadPoolExecutor(2, 2,
1546                                     LONG_DELAY_MS, MILLISECONDS,
1547                                     new ArrayBlockingQueue<Runnable>(10));
1548 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1549 <        l.add(new NPETask());
1550 <        try {
1551 <            e.invokeAny(l);
1552 <            shouldThrow();
1553 <        } catch (ExecutionException success) {
1554 <            assertTrue(success.getCause() instanceof NullPointerException);
1555 <        } finally {
1556 <            joinPool(e);
1548 >        try (PoolCleaner cleaner = cleaner(e)) {
1549 >            List<Callable<String>> l = new ArrayList<>();
1550 >            l.add(new NPETask());
1551 >            try {
1552 >                e.invokeAny(l);
1553 >                shouldThrow();
1554 >            } catch (ExecutionException success) {
1555 >                assertTrue(success.getCause() instanceof NullPointerException);
1556 >            }
1557          }
1558      }
1559  
# Line 1512 | Line 1561 | public class ThreadPoolExecutorTest exte
1561       * invokeAny(c) returns result of some task
1562       */
1563      public void testInvokeAny5() throws Exception {
1564 <        ExecutorService e =
1564 >        final ExecutorService e =
1565              new ThreadPoolExecutor(2, 2,
1566                                     LONG_DELAY_MS, MILLISECONDS,
1567                                     new ArrayBlockingQueue<Runnable>(10));
1568 <        try {
1569 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1568 >        try (PoolCleaner cleaner = cleaner(e)) {
1569 >            List<Callable<String>> l = new ArrayList<>();
1570              l.add(new StringTask());
1571              l.add(new StringTask());
1572              String result = e.invokeAny(l);
1573              assertSame(TEST_STRING, result);
1525        } finally {
1526            joinPool(e);
1574          }
1575      }
1576  
# Line 1531 | Line 1578 | public class ThreadPoolExecutorTest exte
1578       * invokeAll(null) throws NPE
1579       */
1580      public void testInvokeAll1() throws Exception {
1581 <        ExecutorService e =
1581 >        final ExecutorService e =
1582              new ThreadPoolExecutor(2, 2,
1583                                     LONG_DELAY_MS, MILLISECONDS,
1584                                     new ArrayBlockingQueue<Runnable>(10));
1585 <        try {
1586 <            e.invokeAll(null);
1587 <            shouldThrow();
1588 <        } catch (NullPointerException success) {
1589 <        } finally {
1543 <            joinPool(e);
1585 >        try (PoolCleaner cleaner = cleaner(e)) {
1586 >            try {
1587 >                e.invokeAll(null);
1588 >                shouldThrow();
1589 >            } catch (NullPointerException success) {}
1590          }
1591      }
1592  
1593      /**
1594 <     * invokeAll(empty collection) returns empty collection
1594 >     * invokeAll(empty collection) returns empty list
1595       */
1596      public void testInvokeAll2() throws InterruptedException {
1597 <        ExecutorService e =
1597 >        final ExecutorService e =
1598              new ThreadPoolExecutor(2, 2,
1599                                     LONG_DELAY_MS, MILLISECONDS,
1600                                     new ArrayBlockingQueue<Runnable>(10));
1601 <        try {
1602 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1601 >        final Collection<Callable<String>> emptyCollection
1602 >            = Collections.emptyList();
1603 >        try (PoolCleaner cleaner = cleaner(e)) {
1604 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1605              assertTrue(r.isEmpty());
1558        } finally {
1559            joinPool(e);
1606          }
1607      }
1608  
# Line 1564 | Line 1610 | public class ThreadPoolExecutorTest exte
1610       * invokeAll(c) throws NPE if c has null elements
1611       */
1612      public void testInvokeAll3() throws Exception {
1613 <        ExecutorService e =
1613 >        final ExecutorService e =
1614              new ThreadPoolExecutor(2, 2,
1615                                     LONG_DELAY_MS, MILLISECONDS,
1616                                     new ArrayBlockingQueue<Runnable>(10));
1617 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1618 <        l.add(new StringTask());
1619 <        l.add(null);
1620 <        try {
1621 <            e.invokeAll(l);
1622 <            shouldThrow();
1623 <        } catch (NullPointerException success) {
1624 <        } finally {
1579 <            joinPool(e);
1617 >        try (PoolCleaner cleaner = cleaner(e)) {
1618 >            List<Callable<String>> l = new ArrayList<>();
1619 >            l.add(new StringTask());
1620 >            l.add(null);
1621 >            try {
1622 >                e.invokeAll(l);
1623 >                shouldThrow();
1624 >            } catch (NullPointerException success) {}
1625          }
1626      }
1627  
# Line 1584 | Line 1629 | public class ThreadPoolExecutorTest exte
1629       * get of element of invokeAll(c) throws exception on failed task
1630       */
1631      public void testInvokeAll4() throws Exception {
1632 <        ExecutorService e =
1632 >        final ExecutorService e =
1633              new ThreadPoolExecutor(2, 2,
1634                                     LONG_DELAY_MS, MILLISECONDS,
1635                                     new ArrayBlockingQueue<Runnable>(10));
1636 <        try {
1637 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1636 >        try (PoolCleaner cleaner = cleaner(e)) {
1637 >            List<Callable<String>> l = new ArrayList<>();
1638              l.add(new NPETask());
1639              List<Future<String>> futures = e.invokeAll(l);
1640              assertEquals(1, futures.size());
# Line 1599 | Line 1644 | public class ThreadPoolExecutorTest exte
1644              } catch (ExecutionException success) {
1645                  assertTrue(success.getCause() instanceof NullPointerException);
1646              }
1602        } finally {
1603            joinPool(e);
1647          }
1648      }
1649  
# Line 1608 | Line 1651 | public class ThreadPoolExecutorTest exte
1651       * invokeAll(c) returns results of all completed tasks
1652       */
1653      public void testInvokeAll5() throws Exception {
1654 <        ExecutorService e =
1654 >        final ExecutorService e =
1655              new ThreadPoolExecutor(2, 2,
1656                                     LONG_DELAY_MS, MILLISECONDS,
1657                                     new ArrayBlockingQueue<Runnable>(10));
1658 <        try {
1659 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1658 >        try (PoolCleaner cleaner = cleaner(e)) {
1659 >            List<Callable<String>> l = new ArrayList<>();
1660              l.add(new StringTask());
1661              l.add(new StringTask());
1662              List<Future<String>> futures = e.invokeAll(l);
1663              assertEquals(2, futures.size());
1664              for (Future<String> future : futures)
1665                  assertSame(TEST_STRING, future.get());
1623        } finally {
1624            joinPool(e);
1666          }
1667      }
1668  
# Line 1629 | Line 1670 | public class ThreadPoolExecutorTest exte
1670       * timed invokeAny(null) throws NPE
1671       */
1672      public void testTimedInvokeAny1() throws Exception {
1673 <        ExecutorService e =
1673 >        final ExecutorService e =
1674              new ThreadPoolExecutor(2, 2,
1675                                     LONG_DELAY_MS, MILLISECONDS,
1676                                     new ArrayBlockingQueue<Runnable>(10));
1677 <        try {
1678 <            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1679 <            shouldThrow();
1680 <        } catch (NullPointerException success) {
1681 <        } finally {
1641 <            joinPool(e);
1677 >        try (PoolCleaner cleaner = cleaner(e)) {
1678 >            try {
1679 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1680 >                shouldThrow();
1681 >            } catch (NullPointerException success) {}
1682          }
1683      }
1684  
# Line 1646 | Line 1686 | public class ThreadPoolExecutorTest exte
1686       * timed invokeAny(,,null) throws NPE
1687       */
1688      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1689 <        ExecutorService e =
1689 >        final ExecutorService e =
1690              new ThreadPoolExecutor(2, 2,
1691                                     LONG_DELAY_MS, MILLISECONDS,
1692                                     new ArrayBlockingQueue<Runnable>(10));
1693 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1694 <        l.add(new StringTask());
1695 <        try {
1696 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
1697 <            shouldThrow();
1698 <        } catch (NullPointerException success) {
1699 <        } finally {
1660 <            joinPool(e);
1693 >        try (PoolCleaner cleaner = cleaner(e)) {
1694 >            List<Callable<String>> l = new ArrayList<>();
1695 >            l.add(new StringTask());
1696 >            try {
1697 >                e.invokeAny(l, randomTimeout(), null);
1698 >                shouldThrow();
1699 >            } catch (NullPointerException success) {}
1700          }
1701      }
1702  
1703      /**
1704 <     * timed invokeAny(empty collection) throws IAE
1704 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1705       */
1706      public void testTimedInvokeAny2() throws Exception {
1707 <        ExecutorService e =
1707 >        final ExecutorService e =
1708              new ThreadPoolExecutor(2, 2,
1709                                     LONG_DELAY_MS, MILLISECONDS,
1710                                     new ArrayBlockingQueue<Runnable>(10));
1711 <        try {
1712 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1713 <            shouldThrow();
1714 <        } catch (IllegalArgumentException success) {
1715 <        } finally {
1716 <            joinPool(e);
1711 >        try (PoolCleaner cleaner = cleaner(e)) {
1712 >            try {
1713 >                e.invokeAny(new ArrayList<Callable<String>>(),
1714 >                            randomTimeout(), randomTimeUnit());
1715 >                shouldThrow();
1716 >            } catch (IllegalArgumentException success) {}
1717          }
1718      }
1719  
1720      /**
1721 <     * timed invokeAny(c) throws NPE if c has null elements
1721 >     * timed invokeAny(c) throws NullPointerException if c has null elements
1722       */
1723      public void testTimedInvokeAny3() throws Exception {
1724          final CountDownLatch latch = new CountDownLatch(1);
# Line 1687 | Line 1726 | public class ThreadPoolExecutorTest exte
1726              new ThreadPoolExecutor(2, 2,
1727                                     LONG_DELAY_MS, MILLISECONDS,
1728                                     new ArrayBlockingQueue<Runnable>(10));
1729 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1730 <        l.add(latchAwaitingStringTask(latch));
1731 <        l.add(null);
1732 <        try {
1733 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1734 <            shouldThrow();
1735 <        } catch (NullPointerException success) {
1736 <        } finally {
1729 >        try (PoolCleaner cleaner = cleaner(e)) {
1730 >            List<Callable<String>> l = new ArrayList<>();
1731 >            l.add(latchAwaitingStringTask(latch));
1732 >            l.add(null);
1733 >            try {
1734 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1735 >                shouldThrow();
1736 >            } catch (NullPointerException success) {}
1737              latch.countDown();
1699            joinPool(e);
1738          }
1739      }
1740  
# Line 1704 | Line 1742 | public class ThreadPoolExecutorTest exte
1742       * timed invokeAny(c) throws ExecutionException if no task completes
1743       */
1744      public void testTimedInvokeAny4() throws Exception {
1745 <        ExecutorService e =
1745 >        final ExecutorService e =
1746              new ThreadPoolExecutor(2, 2,
1747                                     LONG_DELAY_MS, MILLISECONDS,
1748                                     new ArrayBlockingQueue<Runnable>(10));
1749 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1750 <        l.add(new NPETask());
1751 <        try {
1752 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1753 <            shouldThrow();
1754 <        } catch (ExecutionException success) {
1755 <            assertTrue(success.getCause() instanceof NullPointerException);
1756 <        } finally {
1757 <            joinPool(e);
1749 >        try (PoolCleaner cleaner = cleaner(e)) {
1750 >            long startTime = System.nanoTime();
1751 >            List<Callable<String>> l = new ArrayList<>();
1752 >            l.add(new NPETask());
1753 >            try {
1754 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1755 >                shouldThrow();
1756 >            } catch (ExecutionException success) {
1757 >                assertTrue(success.getCause() instanceof NullPointerException);
1758 >            }
1759 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1760          }
1761      }
1762  
# Line 1724 | Line 1764 | public class ThreadPoolExecutorTest exte
1764       * timed invokeAny(c) returns result of some task
1765       */
1766      public void testTimedInvokeAny5() throws Exception {
1767 <        ExecutorService e =
1767 >        final ExecutorService e =
1768              new ThreadPoolExecutor(2, 2,
1769                                     LONG_DELAY_MS, MILLISECONDS,
1770                                     new ArrayBlockingQueue<Runnable>(10));
1771 <        try {
1772 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1771 >        try (PoolCleaner cleaner = cleaner(e)) {
1772 >            long startTime = System.nanoTime();
1773 >            List<Callable<String>> l = new ArrayList<>();
1774              l.add(new StringTask());
1775              l.add(new StringTask());
1776 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1776 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1777              assertSame(TEST_STRING, result);
1778 <        } finally {
1738 <            joinPool(e);
1778 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1779          }
1780      }
1781  
# Line 1743 | Line 1783 | public class ThreadPoolExecutorTest exte
1783       * timed invokeAll(null) throws NPE
1784       */
1785      public void testTimedInvokeAll1() throws Exception {
1786 <        ExecutorService e =
1786 >        final ExecutorService e =
1787              new ThreadPoolExecutor(2, 2,
1788                                     LONG_DELAY_MS, MILLISECONDS,
1789                                     new ArrayBlockingQueue<Runnable>(10));
1790 <        try {
1791 <            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1792 <            shouldThrow();
1793 <        } catch (NullPointerException success) {
1794 <        } finally {
1755 <            joinPool(e);
1790 >        try (PoolCleaner cleaner = cleaner(e)) {
1791 >            try {
1792 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1793 >                shouldThrow();
1794 >            } catch (NullPointerException success) {}
1795          }
1796      }
1797  
# Line 1760 | Line 1799 | public class ThreadPoolExecutorTest exte
1799       * timed invokeAll(,,null) throws NPE
1800       */
1801      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1802 <        ExecutorService e =
1802 >        final ExecutorService e =
1803              new ThreadPoolExecutor(2, 2,
1804                                     LONG_DELAY_MS, MILLISECONDS,
1805                                     new ArrayBlockingQueue<Runnable>(10));
1806 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1807 <        l.add(new StringTask());
1808 <        try {
1809 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1810 <            shouldThrow();
1811 <        } catch (NullPointerException success) {
1812 <        } finally {
1774 <            joinPool(e);
1806 >        try (PoolCleaner cleaner = cleaner(e)) {
1807 >            List<Callable<String>> l = new ArrayList<>();
1808 >            l.add(new StringTask());
1809 >            try {
1810 >                e.invokeAll(l, randomTimeout(), null);
1811 >                shouldThrow();
1812 >            } catch (NullPointerException success) {}
1813          }
1814      }
1815  
1816      /**
1817 <     * timed invokeAll(empty collection) returns empty collection
1817 >     * timed invokeAll(empty collection) returns empty list
1818       */
1819      public void testTimedInvokeAll2() throws InterruptedException {
1820 <        ExecutorService e =
1820 >        final ExecutorService e =
1821              new ThreadPoolExecutor(2, 2,
1822                                     LONG_DELAY_MS, MILLISECONDS,
1823                                     new ArrayBlockingQueue<Runnable>(10));
1824 <        try {
1825 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1824 >        final Collection<Callable<String>> emptyCollection
1825 >            = Collections.emptyList();
1826 >        try (PoolCleaner cleaner = cleaner(e)) {
1827 >            List<Future<String>> r =
1828 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1829              assertTrue(r.isEmpty());
1789        } finally {
1790            joinPool(e);
1830          }
1831      }
1832  
# Line 1795 | Line 1834 | public class ThreadPoolExecutorTest exte
1834       * timed invokeAll(c) throws NPE if c has null elements
1835       */
1836      public void testTimedInvokeAll3() throws Exception {
1837 <        ExecutorService e =
1837 >        final ExecutorService e =
1838              new ThreadPoolExecutor(2, 2,
1839                                     LONG_DELAY_MS, MILLISECONDS,
1840                                     new ArrayBlockingQueue<Runnable>(10));
1841 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1842 <        l.add(new StringTask());
1843 <        l.add(null);
1844 <        try {
1845 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1846 <            shouldThrow();
1847 <        } catch (NullPointerException success) {
1848 <        } finally {
1810 <            joinPool(e);
1841 >        try (PoolCleaner cleaner = cleaner(e)) {
1842 >            List<Callable<String>> l = new ArrayList<>();
1843 >            l.add(new StringTask());
1844 >            l.add(null);
1845 >            try {
1846 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1847 >                shouldThrow();
1848 >            } catch (NullPointerException success) {}
1849          }
1850      }
1851  
# Line 1815 | Line 1853 | public class ThreadPoolExecutorTest exte
1853       * get of element of invokeAll(c) throws exception on failed task
1854       */
1855      public void testTimedInvokeAll4() throws Exception {
1856 <        ExecutorService e =
1856 >        final ExecutorService e =
1857              new ThreadPoolExecutor(2, 2,
1858                                     LONG_DELAY_MS, MILLISECONDS,
1859                                     new ArrayBlockingQueue<Runnable>(10));
1860 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1861 <        l.add(new NPETask());
1862 <        List<Future<String>> futures =
1863 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1864 <        assertEquals(1, futures.size());
1865 <        try {
1866 <            futures.get(0).get();
1867 <            shouldThrow();
1868 <        } catch (ExecutionException success) {
1869 <            assertTrue(success.getCause() instanceof NullPointerException);
1870 <        } finally {
1871 <            joinPool(e);
1860 >        try (PoolCleaner cleaner = cleaner(e)) {
1861 >            List<Callable<String>> l = new ArrayList<>();
1862 >            l.add(new NPETask());
1863 >            List<Future<String>> futures =
1864 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1865 >            assertEquals(1, futures.size());
1866 >            try {
1867 >                futures.get(0).get();
1868 >                shouldThrow();
1869 >            } catch (ExecutionException success) {
1870 >                assertTrue(success.getCause() instanceof NullPointerException);
1871 >            }
1872          }
1873      }
1874  
# Line 1838 | Line 1876 | public class ThreadPoolExecutorTest exte
1876       * timed invokeAll(c) returns results of all completed tasks
1877       */
1878      public void testTimedInvokeAll5() throws Exception {
1879 <        ExecutorService e =
1879 >        final ExecutorService e =
1880              new ThreadPoolExecutor(2, 2,
1881                                     LONG_DELAY_MS, MILLISECONDS,
1882                                     new ArrayBlockingQueue<Runnable>(10));
1883 <        try {
1884 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1883 >        try (PoolCleaner cleaner = cleaner(e)) {
1884 >            List<Callable<String>> l = new ArrayList<>();
1885              l.add(new StringTask());
1886              l.add(new StringTask());
1887              List<Future<String>> futures =
1888 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1888 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1889              assertEquals(2, futures.size());
1890              for (Future<String> future : futures)
1891                  assertSame(TEST_STRING, future.get());
1854        } finally {
1855            joinPool(e);
1892          }
1893      }
1894  
# Line 1860 | Line 1896 | public class ThreadPoolExecutorTest exte
1896       * timed invokeAll(c) cancels tasks not completed by timeout
1897       */
1898      public void testTimedInvokeAll6() throws Exception {
1899 <        ExecutorService e =
1900 <            new ThreadPoolExecutor(2, 2,
1901 <                                   LONG_DELAY_MS, MILLISECONDS,
1902 <                                   new ArrayBlockingQueue<Runnable>(10));
1903 <        try {
1904 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1905 <            l.add(new StringTask());
1906 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1907 <            l.add(new StringTask());
1908 <            List<Future<String>> futures =
1909 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1910 <            assertEquals(l.size(), futures.size());
1911 <            for (Future future : futures)
1912 <                assertTrue(future.isDone());
1913 <            assertFalse(futures.get(0).isCancelled());
1914 <            assertTrue(futures.get(1).isCancelled());
1915 <        } finally {
1916 <            joinPool(e);
1899 >        for (long timeout = timeoutMillis();;) {
1900 >            final CountDownLatch done = new CountDownLatch(1);
1901 >            final Callable<String> waiter = new CheckedCallable<String>() {
1902 >                public String realCall() {
1903 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1904 >                    catch (InterruptedException ok) {}
1905 >                    return "1"; }};
1906 >            final ExecutorService p =
1907 >                new ThreadPoolExecutor(2, 2,
1908 >                                       LONG_DELAY_MS, MILLISECONDS,
1909 >                                       new ArrayBlockingQueue<Runnable>(10));
1910 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1911 >                List<Callable<String>> tasks = new ArrayList<>();
1912 >                tasks.add(new StringTask("0"));
1913 >                tasks.add(waiter);
1914 >                tasks.add(new StringTask("2"));
1915 >                long startTime = System.nanoTime();
1916 >                List<Future<String>> futures =
1917 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1918 >                assertEquals(tasks.size(), futures.size());
1919 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1920 >                for (Future future : futures)
1921 >                    assertTrue(future.isDone());
1922 >                assertTrue(futures.get(1).isCancelled());
1923 >                try {
1924 >                    assertEquals("0", futures.get(0).get());
1925 >                    assertEquals("2", futures.get(2).get());
1926 >                    break;
1927 >                } catch (CancellationException retryWithLongerTimeout) {
1928 >                    timeout *= 2;
1929 >                    if (timeout >= LONG_DELAY_MS / 2)
1930 >                        fail("expected exactly one task to be cancelled");
1931 >                }
1932 >            }
1933          }
1934      }
1935  
# Line 1891 | Line 1943 | public class ThreadPoolExecutorTest exte
1943                                     LONG_DELAY_MS, MILLISECONDS,
1944                                     new LinkedBlockingQueue<Runnable>(),
1945                                     new FailingThreadFactory());
1946 <        try {
1946 >        try (PoolCleaner cleaner = cleaner(e)) {
1947              final int TASKS = 100;
1948              final CountDownLatch done = new CountDownLatch(TASKS);
1949              for (int k = 0; k < TASKS; ++k)
# Line 1899 | Line 1951 | public class ThreadPoolExecutorTest exte
1951                      public void realRun() {
1952                          done.countDown();
1953                      }});
1954 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1903 <        } finally {
1904 <            joinPool(e);
1954 >            await(done);
1955          }
1956      }
1957  
# Line 1913 | Line 1963 | public class ThreadPoolExecutorTest exte
1963              new ThreadPoolExecutor(2, 2,
1964                                     1000, MILLISECONDS,
1965                                     new ArrayBlockingQueue<Runnable>(10));
1966 <        assertFalse(p.allowsCoreThreadTimeOut());
1967 <        joinPool(p);
1966 >        try (PoolCleaner cleaner = cleaner(p)) {
1967 >            assertFalse(p.allowsCoreThreadTimeOut());
1968 >        }
1969      }
1970  
1971      /**
1972       * allowCoreThreadTimeOut(true) causes idle threads to time out
1973       */
1974      public void testAllowCoreThreadTimeOut_true() throws Exception {
1975 <        long coreThreadTimeOut = SHORT_DELAY_MS;
1975 >        long keepAliveTime = timeoutMillis();
1976          final ThreadPoolExecutor p =
1977              new ThreadPoolExecutor(2, 10,
1978 <                                   coreThreadTimeOut, MILLISECONDS,
1978 >                                   keepAliveTime, MILLISECONDS,
1979                                     new ArrayBlockingQueue<Runnable>(10));
1980 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1981 <        try {
1980 >        try (PoolCleaner cleaner = cleaner(p)) {
1981 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1982              p.allowCoreThreadTimeOut(true);
1983              p.execute(new CheckedRunnable() {
1984                  public void realRun() {
# Line 1935 | Line 1986 | public class ThreadPoolExecutorTest exte
1986                      assertEquals(1, p.getPoolSize());
1987                  }});
1988              await(threadStarted);
1989 <            delay(coreThreadTimeOut);
1989 >            delay(keepAliveTime);
1990              long startTime = System.nanoTime();
1991              while (p.getPoolSize() > 0
1992                     && millisElapsedSince(startTime) < LONG_DELAY_MS)
1993                  Thread.yield();
1994              assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1995              assertEquals(0, p.getPoolSize());
1945        } finally {
1946            joinPool(p);
1996          }
1997      }
1998  
# Line 1951 | Line 2000 | public class ThreadPoolExecutorTest exte
2000       * allowCoreThreadTimeOut(false) causes idle threads not to time out
2001       */
2002      public void testAllowCoreThreadTimeOut_false() throws Exception {
2003 <        long coreThreadTimeOut = SHORT_DELAY_MS;
2003 >        long keepAliveTime = timeoutMillis();
2004          final ThreadPoolExecutor p =
2005              new ThreadPoolExecutor(2, 10,
2006 <                                   coreThreadTimeOut, MILLISECONDS,
2006 >                                   keepAliveTime, MILLISECONDS,
2007                                     new ArrayBlockingQueue<Runnable>(10));
2008 <        final CountDownLatch threadStarted = new CountDownLatch(1);
2009 <        try {
2008 >        try (PoolCleaner cleaner = cleaner(p)) {
2009 >            final CountDownLatch threadStarted = new CountDownLatch(1);
2010              p.allowCoreThreadTimeOut(false);
2011              p.execute(new CheckedRunnable() {
2012                  public void realRun() throws InterruptedException {
2013                      threadStarted.countDown();
2014                      assertTrue(p.getPoolSize() >= 1);
2015                  }});
2016 <            delay(2 * coreThreadTimeOut);
2016 >            delay(2 * keepAliveTime);
2017              assertTrue(p.getPoolSize() >= 1);
1969        } finally {
1970            joinPool(p);
2018          }
2019      }
2020  
# Line 1983 | Line 2030 | public class ThreadPoolExecutorTest exte
2030                  done.countDown();
2031              }};
2032          final ThreadPoolExecutor p =
2033 <            new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS,
2033 >            new ThreadPoolExecutor(1, 30,
2034 >                                   60, SECONDS,
2035                                     new ArrayBlockingQueue(30));
2036 <        try {
2036 >        try (PoolCleaner cleaner = cleaner(p)) {
2037              for (int i = 0; i < nTasks; ++i) {
2038                  for (;;) {
2039                      try {
# Line 1996 | Line 2044 | public class ThreadPoolExecutorTest exte
2044                  }
2045              }
2046              // enough time to run all tasks
2047 <            assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2000 <        } finally {
2001 <            joinPool(p);
2047 >            await(done, nTasks * SHORT_DELAY_MS);
2048          }
2049      }
2050  
2051 +    /**
2052 +     * get(cancelled task) throws CancellationException
2053 +     */
2054 +    public void testGet_cancelled() throws Exception {
2055 +        final CountDownLatch done = new CountDownLatch(1);
2056 +        final ExecutorService e =
2057 +            new ThreadPoolExecutor(1, 1,
2058 +                                   LONG_DELAY_MS, MILLISECONDS,
2059 +                                   new LinkedBlockingQueue<Runnable>());
2060 +        try (PoolCleaner cleaner = cleaner(e, done)) {
2061 +            final CountDownLatch blockerStarted = new CountDownLatch(1);
2062 +            final List<Future<?>> futures = new ArrayList<>();
2063 +            for (int i = 0; i < 2; i++) {
2064 +                Runnable r = new CheckedRunnable() { public void realRun()
2065 +                                                         throws Throwable {
2066 +                    blockerStarted.countDown();
2067 +                    assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
2068 +                }};
2069 +                futures.add(e.submit(r));
2070 +            }
2071 +            await(blockerStarted);
2072 +            for (Future<?> future : futures) future.cancel(false);
2073 +            for (Future<?> future : futures) {
2074 +                try {
2075 +                    future.get();
2076 +                    shouldThrow();
2077 +                } catch (CancellationException success) {}
2078 +                try {
2079 +                    future.get(LONG_DELAY_MS, MILLISECONDS);
2080 +                    shouldThrow();
2081 +                } catch (CancellationException success) {}
2082 +                assertTrue(future.isCancelled());
2083 +                assertTrue(future.isDone());
2084 +            }
2085 +        }
2086 +    }
2087 +
2088 +    /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
2089 +    public void testStandardRejectedExecutionHandlers() {
2090 +        final ThreadPoolExecutor p =
2091 +            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2092 +                                   new ArrayBlockingQueue<Runnable>(1));
2093 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2094 +        final Runnable r = new Runnable() { public void run() {
2095 +            thread.set(Thread.currentThread()); }};
2096 +
2097 +        try {
2098 +            new AbortPolicy().rejectedExecution(r, p);
2099 +            shouldThrow();
2100 +        } catch (RejectedExecutionException success) {}
2101 +        assertNull(thread.get());
2102 +
2103 +        new DiscardPolicy().rejectedExecution(r, p);
2104 +        assertNull(thread.get());
2105 +
2106 +        new CallerRunsPolicy().rejectedExecution(r, p);
2107 +        assertSame(Thread.currentThread(), thread.get());
2108 +
2109 +        // check that pool was not perturbed by handlers
2110 +        assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
2111 +        assertEquals(0, p.getTaskCount());
2112 +        assertTrue(p.getQueue().isEmpty());
2113 +    }
2114 +
2115   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines