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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines