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.8 by dl, Sun Oct 5 23:00:40 2003 UTC vs.
Revision 1.74 by jsr166, Sun Oct 4 01:58:38 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines