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.18 by dl, Tue Jan 20 20:30:08 2004 UTC vs.
Revision 1.115 by jsr166, Mon Mar 20 00:21:54 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines