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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines