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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines