--- jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java 2010/11/17 23:12:31 1.23 +++ jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java 2015/10/04 02:24:49 1.67 @@ -1,21 +1,45 @@ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/licenses/publicdomain + * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ -import java.util.concurrent.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.concurrent.locks.*; +import static java.util.concurrent.TimeUnit.SECONDS; -import junit.framework.*; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +import junit.framework.Test; +import junit.framework.TestSuite; public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); + main(suite(), args); } public static Test suite() { return new TestSuite(ThreadPoolExecutorSubclassTest.class); @@ -37,7 +61,7 @@ public class ThreadPoolExecutorSubclassT CustomTask(final Runnable r, final V res) { if (r == null) throw new NullPointerException(); callable = new Callable() { - public V call() throws Exception { r.run(); return res; }}; + public V call() throws Exception { r.run(); return res; }}; } public boolean isDone() { lock.lock(); try { return done; } finally { lock.unlock() ; } @@ -77,11 +101,13 @@ public class ThreadPoolExecutorSubclassT } lock.lock(); try { - result = v; - exception = e; - done = true; - thread = null; - cond.signalAll(); + if (!done) { + result = v; + exception = e; + done = true; + thread = null; + cond.signalAll(); + } } finally { lock.unlock(); } } @@ -90,6 +116,8 @@ public class ThreadPoolExecutorSubclassT try { while (!done) cond.await(); + if (cancelled) + throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; @@ -101,12 +129,13 @@ public class ThreadPoolExecutorSubclassT long nanos = unit.toNanos(timeout); lock.lock(); try { - for (;;) { - if (done) break; - if (nanos < 0) + while (!done) { + if (nanos <= 0L) throw new TimeoutException(); nanos = cond.awaitNanos(nanos); } + if (cancelled) + throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; @@ -115,7 +144,6 @@ public class ThreadPoolExecutorSubclassT } } - static class CustomTPE extends ThreadPoolExecutor { protected RunnableFuture newTaskFor(Callable c) { return new CustomTask(c); @@ -162,22 +190,32 @@ public class ThreadPoolExecutorSubclassT workQueue, threadFactory, handler); } - volatile boolean beforeCalled = false; - volatile boolean afterCalled = false; - volatile boolean terminatedCalled = false; + final CountDownLatch beforeCalled = new CountDownLatch(1); + final CountDownLatch afterCalled = new CountDownLatch(1); + final CountDownLatch terminatedCalled = new CountDownLatch(1); + public CustomTPE() { super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue()); } protected void beforeExecute(Thread t, Runnable r) { - beforeCalled = true; + beforeCalled.countDown(); } protected void afterExecute(Runnable r, Throwable t) { - afterCalled = true; + afterCalled.countDown(); } protected void terminated() { - terminatedCalled = true; + terminatedCalled.countDown(); } + public boolean beforeCalled() { + return beforeCalled.getCount() == 0; + } + public boolean afterCalled() { + return afterCalled.getCount() == 0; + } + public boolean terminatedCalled() { + return terminatedCalled.getCount() == 0; + } } static class FailingThreadFactory implements ThreadFactory { @@ -188,25 +226,20 @@ public class ThreadPoolExecutorSubclassT } } - /** * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { final ThreadPoolExecutor p = new CustomTPE(1, 1, - LONG_DELAY_MS, MILLISECONDS, + 2 * LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch done = new CountDownLatch(1); - final Runnable task = new CheckedRunnable() { - public void realRun() { - done.countDown(); - }}; - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + final Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; p.execute(task); - assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS)); - } finally { - joinPool(p); + assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); } } @@ -219,9 +252,9 @@ public class ThreadPoolExecutorSubclassT new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); assertEquals(0, p.getActiveCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -229,11 +262,9 @@ public class ThreadPoolExecutorSubclassT assertEquals(1, p.getActiveCount()); done.await(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertEquals(1, p.getActiveCount()); - } finally { done.countDown(); - joinPool(p); } } @@ -241,28 +272,48 @@ public class ThreadPoolExecutorSubclassT * prestartCoreThread starts a thread if under corePoolSize, else doesn't */ public void testPrestartCoreThread() { - ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p.getPoolSize()); - assertTrue(p.prestartCoreThread()); - assertEquals(1, p.getPoolSize()); - assertTrue(p.prestartCoreThread()); - assertEquals(2, p.getPoolSize()); - assertFalse(p.prestartCoreThread()); - assertEquals(2, p.getPoolSize()); - joinPool(p); + ThreadPoolExecutor p = + new CustomTPE(2, 6, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(0, p.getPoolSize()); + assertTrue(p.prestartCoreThread()); + assertEquals(1, p.getPoolSize()); + assertTrue(p.prestartCoreThread()); + assertEquals(2, p.getPoolSize()); + assertFalse(p.prestartCoreThread()); + assertEquals(2, p.getPoolSize()); + p.setCorePoolSize(4); + assertTrue(p.prestartCoreThread()); + assertEquals(3, p.getPoolSize()); + assertTrue(p.prestartCoreThread()); + assertEquals(4, p.getPoolSize()); + assertFalse(p.prestartCoreThread()); + assertEquals(4, p.getPoolSize()); + } } /** * prestartAllCoreThreads starts all corePoolSize threads */ public void testPrestartAllCoreThreads() { - ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p.getPoolSize()); - p.prestartAllCoreThreads(); - assertEquals(2, p.getPoolSize()); - p.prestartAllCoreThreads(); - assertEquals(2, p.getPoolSize()); - joinPool(p); + ThreadPoolExecutor p = + new CustomTPE(2, 6, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(0, p.getPoolSize()); + p.prestartAllCoreThreads(); + assertEquals(2, p.getPoolSize()); + p.prestartAllCoreThreads(); + assertEquals(2, p.getPoolSize()); + p.setCorePoolSize(4); + p.prestartAllCoreThreads(); + assertEquals(4, p.getPoolSize()); + p.prestartAllCoreThreads(); + assertEquals(4, p.getPoolSize()); + } } /** @@ -274,10 +325,10 @@ public class ThreadPoolExecutorSubclassT new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch threadProceed = new CountDownLatch(1); - final CountDownLatch threadDone = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch threadProceed = new CountDownLatch(1); + final CountDownLatch threadDone = new CountDownLatch(1); assertEquals(0, p.getCompletedTaskCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -286,14 +337,16 @@ public class ThreadPoolExecutorSubclassT threadProceed.await(); threadDone.countDown(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(0, p.getCompletedTaskCount()); threadProceed.countDown(); threadDone.await(); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(1, p.getCompletedTaskCount()); - } finally { - joinPool(p); + long startTime = System.nanoTime(); + while (p.getCompletedTaskCount() != 1) { + if (millisElapsedSince(startTime) > LONG_DELAY_MS) + fail("timed out"); + Thread.yield(); + } } } @@ -301,54 +354,72 @@ public class ThreadPoolExecutorSubclassT * getCorePoolSize returns size given in constructor if not otherwise set */ public void testGetCorePoolSize() { - ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p.getCorePoolSize()); - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getCorePoolSize()); + } } /** * getKeepAliveTime returns value given in constructor if not otherwise set */ public void testGetKeepAliveTime() { - ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p.getKeepAliveTime(TimeUnit.SECONDS)); - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(2, 2, + 1000, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getKeepAliveTime(SECONDS)); + } } - /** * getThreadFactory returns factory in constructor if not set */ public void testGetThreadFactory() { - ThreadFactory tf = new SimpleThreadFactory(); - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10), tf, new NoOpREHandler()); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + final ThreadFactory threadFactory = new SimpleThreadFactory(); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10), + threadFactory, + new NoOpREHandler()); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(threadFactory, p.getThreadFactory()); + } } /** * setThreadFactory sets the thread factory returned by getThreadFactory */ public void testSetThreadFactory() { - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - ThreadFactory tf = new SimpleThreadFactory(); - p.setThreadFactory(tf); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + ThreadFactory threadFactory = new SimpleThreadFactory(); + p.setThreadFactory(threadFactory); + assertSame(threadFactory, p.getThreadFactory()); + } } - /** * setThreadFactory(null) throws NPE */ public void testSetThreadFactoryNull() { - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setThreadFactory(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setThreadFactory(null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -356,10 +427,15 @@ public class ThreadPoolExecutorSubclassT * getRejectedExecutionHandler returns handler in constructor if not set */ public void testGetRejectedExecutionHandler() { - RejectedExecutionHandler h = new NoOpREHandler(); - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10), h); - assertSame(h, p.getRejectedExecutionHandler()); - joinPool(p); + final RejectedExecutionHandler handler = new NoOpREHandler(); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10), + handler); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(handler, p.getRejectedExecutionHandler()); + } } /** @@ -367,29 +443,33 @@ public class ThreadPoolExecutorSubclassT * getRejectedExecutionHandler */ public void testSetRejectedExecutionHandler() { - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - RejectedExecutionHandler h = new NoOpREHandler(); - p.setRejectedExecutionHandler(h); - assertSame(h, p.getRejectedExecutionHandler()); - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + RejectedExecutionHandler handler = new NoOpREHandler(); + p.setRejectedExecutionHandler(handler); + assertSame(handler, p.getRejectedExecutionHandler()); + } } - /** * setRejectedExecutionHandler(null) throws NPE */ public void testSetRejectedExecutionHandlerNull() { - ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setRejectedExecutionHandler(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setRejectedExecutionHandler(null); + shouldThrow(); + } catch (NullPointerException success) {} } } - /** * getLargestPoolSize increases, but doesn't overestimate, when * multiple threads active @@ -400,9 +480,9 @@ public class ThreadPoolExecutorSubclassT new CustomTPE(THREADS, THREADS, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadsStarted = new CountDownLatch(THREADS); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadsStarted = new CountDownLatch(THREADS); + final CountDownLatch done = new CountDownLatch(1); assertEquals(0, p.getLargestPoolSize()); for (int i = 0; i < THREADS; i++) p.execute(new CheckedRunnable() { @@ -411,13 +491,11 @@ public class ThreadPoolExecutorSubclassT done.await(); assertEquals(THREADS, p.getLargestPoolSize()); }}); - assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS)); - assertEquals(THREADS, p.getLargestPoolSize()); - } finally { - done.countDown(); - joinPool(p); + assertTrue(threadsStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertEquals(THREADS, p.getLargestPoolSize()); + done.countDown(); // release pool } + assertEquals(THREADS, p.getLargestPoolSize()); } /** @@ -425,9 +503,17 @@ public class ThreadPoolExecutorSubclassT * otherwise set */ public void testGetMaximumPoolSize() { - ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(2, p.getMaximumPoolSize()); - joinPool(p); + final ThreadPoolExecutor p = + new CustomTPE(2, 3, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(3, p.getMaximumPoolSize()); + p.setMaximumPoolSize(5); + assertEquals(5, p.getMaximumPoolSize()); + p.setMaximumPoolSize(4); + assertEquals(4, p.getMaximumPoolSize()); + } } /** @@ -439,9 +525,9 @@ public class ThreadPoolExecutorSubclassT new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); assertEquals(0, p.getPoolSize()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -449,11 +535,9 @@ public class ThreadPoolExecutorSubclassT assertEquals(1, p.getPoolSize()); done.await(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertEquals(1, p.getPoolSize()); - } finally { - done.countDown(); - joinPool(p); + done.countDown(); // release pool } } @@ -465,9 +549,9 @@ public class ThreadPoolExecutorSubclassT new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); assertEquals(0, p.getTaskCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -475,16 +559,14 @@ public class ThreadPoolExecutorSubclassT assertEquals(1, p.getTaskCount()); done.await(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertEquals(1, p.getTaskCount()); - } finally { done.countDown(); - joinPool(p); } } /** - * isShutDown is false before shutdown, true after + * isShutdown is false before shutdown, true after */ public void testIsShutdown() { @@ -495,7 +577,6 @@ public class ThreadPoolExecutorSubclassT joinPool(p); } - /** * isTerminated is false before termination, true after */ @@ -510,11 +591,11 @@ public class ThreadPoolExecutorSubclassT assertFalse(p.isTerminating()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { - threadStarted.countDown(); assertFalse(p.isTerminating()); + threadStarted.countDown(); done.await(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertFalse(p.isTerminating()); done.countDown(); } finally { @@ -543,7 +624,7 @@ public class ThreadPoolExecutorSubclassT threadStarted.countDown(); done.await(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertFalse(p.isTerminating()); done.countDown(); } finally { @@ -578,7 +659,7 @@ public class ThreadPoolExecutorSubclassT tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertSame(q, p.getQueue()); assertFalse(q.contains(tasks[0])); assertTrue(q.contains(tasks[tasks.length - 1])); @@ -610,7 +691,7 @@ public class ThreadPoolExecutorSubclassT }}; p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertFalse(p.remove(tasks[0])); assertTrue(q.contains(tasks[4])); assertTrue(q.contains(tasks[3])); @@ -649,7 +730,7 @@ public class ThreadPoolExecutorSubclassT tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); assertEquals(tasks.length, p.getTaskCount()); assertEquals(tasks.length - 1, q.size()); assertEquals(1L, p.getActiveCount()); @@ -669,33 +750,53 @@ public class ThreadPoolExecutorSubclassT } /** - * shutDownNow returns a list containing tasks that were not run + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue */ - public void testShutDownNow() { - ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List l; - try { - for (int i = 0; i < 5; i++) - p.execute(new MediumPossiblyInterruptedRunnable()); - } - finally { + public void testShutdownNow() throws InterruptedException { + final int poolSize = 2; + final int count = 5; + final AtomicInteger ran = new AtomicInteger(0); + ThreadPoolExecutor p = + new CustomTPE(poolSize, poolSize, LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + CountDownLatch threadsStarted = new CountDownLatch(poolSize); + Runnable waiter = new CheckedRunnable() { public void realRun() { + threadsStarted.countDown(); try { - l = p.shutdownNow(); - } catch (SecurityException ok) { return; } + MILLISECONDS.sleep(2 * LONG_DELAY_MS); + } catch (InterruptedException success) {} + ran.getAndIncrement(); + }}; + for (int i = 0; i < count; i++) + p.execute(waiter); + assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(poolSize, p.getActiveCount()); + assertEquals(0, p.getCompletedTaskCount()); + final List queuedTasks; + try { + queuedTasks = p.shutdownNow(); + } catch (SecurityException ok) { + return; // Allowed in case test doesn't have privs } assertTrue(p.isShutdown()); - assertTrue(l.size() <= 4); + assertTrue(p.getQueue().isEmpty()); + assertEquals(count - poolSize, queuedTasks.size()); + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertEquals(poolSize, ran.get()); + assertEquals(poolSize, p.getCompletedTaskCount()); } // Exception Tests - /** * Constructor throws if corePoolSize argument is less than zero */ public void testConstructor1() { try { - new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new CustomTPE(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -705,7 +806,8 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor2() { try { - new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new CustomTPE(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -715,7 +817,8 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor3() { try { - new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new CustomTPE(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -725,7 +828,8 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor4() { try { - new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10)); + new CustomTPE(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -735,7 +839,8 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor5() { try { - new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new CustomTPE(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -745,19 +850,19 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException() { try { - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null); + new CustomTPE(1, 2, 1L, SECONDS, null); shouldThrow(); } catch (NullPointerException success) {} } - - /** * Constructor throws if corePoolSize argument is less than zero */ public void testConstructor6() { try { - new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new CustomTPE(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -767,7 +872,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor7() { try { - new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new CustomTPE(1,-1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -777,7 +884,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor8() { try { - new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new CustomTPE(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -787,7 +896,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor9() { try { - new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new CustomTPE(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -797,7 +908,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor10() { try { - new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new CustomTPE(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -807,7 +920,7 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException2() { try { - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory()); + new CustomTPE(1, 2, 1L, SECONDS, null, new SimpleThreadFactory()); shouldThrow(); } catch (NullPointerException success) {} } @@ -817,19 +930,21 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException3() { try { - ThreadFactory f = null; - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),f); + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10), + (ThreadFactory) null); shouldThrow(); } catch (NullPointerException success) {} } - /** * Constructor throws if corePoolSize argument is less than zero */ public void testConstructor11() { try { - new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new CustomTPE(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -839,7 +954,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor12() { try { - new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new CustomTPE(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -849,7 +966,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor13() { try { - new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new CustomTPE(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -859,7 +978,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor14() { try { - new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new CustomTPE(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -869,7 +990,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor15() { try { - new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new CustomTPE(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -879,7 +1002,9 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException4() { try { - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new NoOpREHandler()); + new CustomTPE(1, 2, 1L, SECONDS, + null, + new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} } @@ -889,19 +1014,22 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException5() { try { - RejectedExecutionHandler r = null; - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),r); + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10), + (RejectedExecutionHandler) null); shouldThrow(); } catch (NullPointerException success) {} } - /** * Constructor throws if corePoolSize argument is less than zero */ public void testConstructor16() { try { - new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -911,7 +1039,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor17() { try { - new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -921,7 +1052,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor18() { try { - new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -931,7 +1065,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor19() { try { - new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -941,7 +1078,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructor20() { try { - new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -951,7 +1091,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException6() { try { - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler()); + new CustomTPE(1, 2, 1L, SECONDS, + null, + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} } @@ -961,8 +1104,10 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException7() { try { - RejectedExecutionHandler r = null; - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),new SimpleThreadFactory(),r); + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + (RejectedExecutionHandler) null); shouldThrow(); } catch (NullPointerException success) {} } @@ -972,8 +1117,7 @@ public class ThreadPoolExecutorSubclassT */ public void testConstructorNullPointerException8() { try { - new CustomTPE(1, 2, - LONG_DELAY_MS, MILLISECONDS, + new CustomTPE(1, 2, 1L, SECONDS, new ArrayBlockingQueue(10), (ThreadFactory) null, new NoOpREHandler()); @@ -981,7 +1125,6 @@ public class ThreadPoolExecutorSubclassT } catch (NullPointerException success) {} } - /** * execute throws RejectedExecutionException if saturated. */ @@ -1131,7 +1274,6 @@ public class ThreadPoolExecutorSubclassT } } - /** * execute using DiscardOldestPolicy drops task on shutdown */ @@ -1149,14 +1291,14 @@ public class ThreadPoolExecutorSubclassT } } - /** * execute(null) throws NPE */ public void testExecuteNull() { - ThreadPoolExecutor p = null; + ThreadPoolExecutor p = + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10)); try { - p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); p.execute(null); shouldThrow(); } catch (NullPointerException success) {} @@ -1214,7 +1356,6 @@ public class ThreadPoolExecutorSubclassT joinPool(p); } - /** * setKeepAliveTime throws IllegalArgumentException * when given a negative value @@ -1239,7 +1380,7 @@ public class ThreadPoolExecutorSubclassT public void testTerminated() { CustomTPE p = new CustomTPE(); try { p.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p.terminatedCalled); + assertTrue(p.terminatedCalled()); joinPool(p); } @@ -1249,12 +1390,15 @@ public class ThreadPoolExecutorSubclassT public void testBeforeAfter() throws InterruptedException { CustomTPE p = new CustomTPE(); try { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - p.execute(r); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(r.done); - assertTrue(p.beforeCalled); - assertTrue(p.afterCalled); + final CountDownLatch done = new CountDownLatch(1); + p.execute(new CheckedRunnable() { + public void realRun() { + done.countDown(); + }}); + await(p.afterCalled); + assertEquals(0, done.getCount()); + assertTrue(p.afterCalled()); + assertTrue(p.beforeCalled()); try { p.shutdown(); } catch (SecurityException ok) { return; } } finally { joinPool(p); @@ -1303,7 +1447,6 @@ public class ThreadPoolExecutorSubclassT } } - /** * invokeAny(null) throws NPE */ @@ -1465,8 +1608,6 @@ public class ThreadPoolExecutorSubclassT } } - - /** * timed invokeAny(null) throws NPE */ @@ -1653,7 +1794,7 @@ public class ThreadPoolExecutorSubclassT l.add(new StringTask()); l.add(new StringTask()); List> futures = - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); assertEquals(2, futures.size()); for (Future future : futures) assertSame(TEST_STRING, future.get()); @@ -1668,22 +1809,29 @@ public class ThreadPoolExecutorSubclassT public void testTimedInvokeAll6() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING)); - l.add(new StringTask()); - List> futures = - e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS); - assertEquals(3, futures.size()); - Iterator> it = futures.iterator(); - Future f1 = it.next(); - Future f2 = it.next(); - Future f3 = it.next(); - assertTrue(f1.isDone()); - assertTrue(f2.isDone()); - assertTrue(f3.isDone()); - assertFalse(f1.isCancelled()); - assertTrue(f2.isCancelled()); + for (long timeout = timeoutMillis();;) { + List> tasks = new ArrayList<>(); + tasks.add(new StringTask("0")); + tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING)); + tasks.add(new StringTask("2")); + long startTime = System.nanoTime(); + List> futures = + e.invokeAll(tasks, timeout, MILLISECONDS); + assertEquals(tasks.size(), futures.size()); + assertTrue(millisElapsedSince(startTime) >= timeout); + for (Future future : futures) + assertTrue(future.isDone()); + assertTrue(futures.get(1).isCancelled()); + try { + assertEquals("0", futures.get(0).get()); + assertEquals("2", futures.get(2).get()); + break; + } catch (CancellationException retryWithLongerTimeout) { + timeout *= 2; + if (timeout >= LONG_DELAY_MS / 2) + fail("expected exactly one task to be cancelled"); + } + } } finally { joinPool(e); } @@ -1726,24 +1874,26 @@ public class ThreadPoolExecutorSubclassT * allowCoreThreadTimeOut(true) causes idle threads to time out */ public void testAllowCoreThreadTimeOut_true() throws Exception { + long keepAliveTime = timeoutMillis(); final ThreadPoolExecutor p = new CustomTPE(2, 10, - SHORT_DELAY_MS, MILLISECONDS, + keepAliveTime, MILLISECONDS, new ArrayBlockingQueue(10)); final CountDownLatch threadStarted = new CountDownLatch(1); try { p.allowCoreThreadTimeOut(true); p.execute(new CheckedRunnable() { - public void realRun() throws InterruptedException { + public void realRun() { threadStarted.countDown(); assertEquals(1, p.getPoolSize()); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); - for (int i = 0; i < (MEDIUM_DELAY_MS/10); i++) { - if (p.getPoolSize() == 0) - break; - Thread.sleep(10); - } + await(threadStarted); + delay(keepAliveTime); + long startTime = System.nanoTime(); + while (p.getPoolSize() > 0 + && millisElapsedSince(startTime) < LONG_DELAY_MS) + Thread.yield(); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); assertEquals(0, p.getPoolSize()); } finally { joinPool(p); @@ -1754,9 +1904,10 @@ public class ThreadPoolExecutorSubclassT * allowCoreThreadTimeOut(false) causes idle threads not to time out */ public void testAllowCoreThreadTimeOut_false() throws Exception { + long keepAliveTime = timeoutMillis(); final ThreadPoolExecutor p = new CustomTPE(2, 10, - SHORT_DELAY_MS, MILLISECONDS, + keepAliveTime, MILLISECONDS, new ArrayBlockingQueue(10)); final CountDownLatch threadStarted = new CountDownLatch(1); try { @@ -1766,11 +1917,52 @@ public class ThreadPoolExecutorSubclassT threadStarted.countDown(); assertTrue(p.getPoolSize() >= 1); }}); - Thread.sleep(SMALL_DELAY_MS); + delay(2 * keepAliveTime); assertTrue(p.getPoolSize() >= 1); } finally { joinPool(p); } } + /** + * get(cancelled task) throws CancellationException + * (in part, a test of CustomTPE itself) + */ + public void testGet_cancelled() throws Exception { + final ExecutorService e = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new LinkedBlockingQueue()); + try { + final CountDownLatch blockerStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + final List> futures = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + Runnable r = new CheckedRunnable() { public void realRun() + throws Throwable { + blockerStarted.countDown(); + assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS)); + }}; + futures.add(e.submit(r)); + } + assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS)); + for (Future future : futures) future.cancel(false); + for (Future future : futures) { + try { + future.get(); + shouldThrow(); + } catch (CancellationException success) {} + try { + future.get(LONG_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (CancellationException success) {} + assertTrue(future.isCancelled()); + assertTrue(future.isDone()); + } + done.countDown(); + } finally { + joinPool(e); + } + } + }