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.23 by dl, Tue Aug 23 12:50:00 2005 UTC vs.
Revision 1.112 by jsr166, Thu Oct 8 03:08:38 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines