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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines