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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines