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.29 by jsr166, Fri Nov 20 16:02:10 2009 UTC vs.
Revision 1.100 by jsr166, Mon Oct 5 21:42:49 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines