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.43 by jsr166, Sat May 7 19:49:37 2011 UTC vs.
Revision 1.120 by jsr166, Sat Jul 15 18:17:40 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines