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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines