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.9 by dl, Sun Oct 5 23:55:03 2003 UTC vs.
Revision 1.115 by jsr166, Mon Mar 20 00:21:54 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines