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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines