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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines