ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java
(Generate patch)

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines