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.31 by jsr166, Sat Nov 21 02:07:27 2009 UTC vs.
Revision 1.115 by jsr166, Mon Mar 20 00:21:54 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines