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.30 by jsr166, Fri Nov 20 22:58:48 2009 UTC vs.
Revision 1.86 by jsr166, Sun Oct 4 02:34:48 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines