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.85 by jsr166, Sun Oct 4 02:33:09 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines