--- jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java 2009/11/21 20:17:40 1.15 +++ jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java 2015/10/04 01:30:27 1.56 @@ -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() ; } @@ -60,15 +84,13 @@ public class ThreadPoolExecutorSubclassT finally { lock.unlock() ; } } public void run() { - boolean runme; lock.lock(); try { - runme = !done; - if (!runme) - thread = Thread.currentThread(); + if (done) + return; + thread = Thread.currentThread(); } finally { lock.unlock() ; } - if (!runme) return; V v = null; Exception e = null; try { @@ -79,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(); } } @@ -92,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; @@ -103,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; @@ -117,7 +144,6 @@ public class ThreadPoolExecutorSubclassT } } - static class CustomTPE extends ThreadPoolExecutor { protected RunnableFuture newTaskFor(Callable c) { return new CustomTask(c); @@ -164,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 { @@ -190,94 +226,156 @@ public class ThreadPoolExecutorSubclassT } } - /** - * execute successfully executes a runnable + * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p1.execute(new ShortRunnable()); - Thread.sleep(SMALL_DELAY_MS); - } finally { - joinPool(p1); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + 2 * LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + 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(LONG_DELAY_MS, MILLISECONDS)); } } /** - * getActiveCount increases but doesn't overestimate, when a - * thread becomes active + * getActiveCount increases but doesn't overestimate, when a + * thread becomes active */ public void testGetActiveCount() throws InterruptedException { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p2.getActiveCount()); - p2.execute(new MediumRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(1, p2.getActiveCount()); - joinPool(p2); + final ThreadPoolExecutor p = + new CustomTPE(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(0, p.getActiveCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getActiveCount()); + done.await(); + }}); + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertEquals(1, p.getActiveCount()); + done.countDown(); + } } /** - * prestartCoreThread starts a thread if under corePoolSize, else doesn't + * prestartCoreThread starts a thread if under corePoolSize, else doesn't */ public void testPrestartCoreThread() { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p2.getPoolSize()); - assertTrue(p2.prestartCoreThread()); - assertEquals(1, p2.getPoolSize()); - assertTrue(p2.prestartCoreThread()); - assertEquals(2, p2.getPoolSize()); - assertFalse(p2.prestartCoreThread()); - assertEquals(2, p2.getPoolSize()); - joinPool(p2); + 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 + * prestartAllCoreThreads starts all corePoolSize threads */ public void testPrestartAllCoreThreads() { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p2.getPoolSize()); - p2.prestartAllCoreThreads(); - assertEquals(2, p2.getPoolSize()); - p2.prestartAllCoreThreads(); - assertEquals(2, p2.getPoolSize()); - joinPool(p2); + 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()); + } } /** - * getCompletedTaskCount increases, but doesn't overestimate, - * when tasks complete + * getCompletedTaskCount increases, but doesn't overestimate, + * when tasks complete */ public void testGetCompletedTaskCount() throws InterruptedException { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p2.getCompletedTaskCount()); - p2.execute(new ShortRunnable()); - Thread.sleep(SMALL_DELAY_MS); - assertEquals(1, p2.getCompletedTaskCount()); - try { p2.shutdown(); } catch (SecurityException ok) { return; } - joinPool(p2); + final ThreadPoolExecutor p = + new CustomTPE(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + 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 { + threadStarted.countDown(); + assertEquals(0, p.getCompletedTaskCount()); + threadProceed.await(); + threadDone.countDown(); + }}); + await(threadStarted); + assertEquals(0, p.getCompletedTaskCount()); + threadProceed.countDown(); + threadDone.await(); + long startTime = System.nanoTime(); + while (p.getCompletedTaskCount() != 1) { + if (millisElapsedSince(startTime) > LONG_DELAY_MS) + fail("timed out"); + Thread.yield(); + } + } } /** - * getCorePoolSize returns size given in constructor if not otherwise set + * getCorePoolSize returns size given in constructor if not otherwise set */ public void testGetCorePoolSize() { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p1.getCorePoolSize()); - joinPool(p1); + 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 + * getKeepAliveTime returns value given in constructor if not otherwise set */ public void testGetKeepAliveTime() { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS)); - joinPool(p2); + 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 */ @@ -299,7 +397,6 @@ public class ThreadPoolExecutorSubclassT joinPool(p); } - /** * setThreadFactory(null) throws NPE */ @@ -336,7 +433,6 @@ public class ThreadPoolExecutorSubclassT joinPool(p); } - /** * setRejectedExecutionHandler(null) throws NPE */ @@ -351,122 +447,201 @@ public class ThreadPoolExecutorSubclassT } } - /** - * getLargestPoolSize increases, but doesn't overestimate, when - * multiple threads active + * getLargestPoolSize increases, but doesn't overestimate, when + * multiple threads active */ public void testGetLargestPoolSize() throws InterruptedException { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p2.getLargestPoolSize()); - p2.execute(new MediumRunnable()); - p2.execute(new MediumRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(2, p2.getLargestPoolSize()); - joinPool(p2); + final int THREADS = 3; + final ThreadPoolExecutor p = + new CustomTPE(THREADS, THREADS, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadsStarted = new CountDownLatch(THREADS); + final CountDownLatch done = new CountDownLatch(1); + try { + assertEquals(0, p.getLargestPoolSize()); + for (int i = 0; i < THREADS; i++) + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadsStarted.countDown(); + done.await(); + assertEquals(THREADS, p.getLargestPoolSize()); + }}); + assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertEquals(THREADS, p.getLargestPoolSize()); + } finally { + done.countDown(); + joinPool(p); + assertEquals(THREADS, p.getLargestPoolSize()); + } } /** - * getMaximumPoolSize returns value given in constructor if not - * otherwise set + * getMaximumPoolSize returns value given in constructor if not + * otherwise set */ public void testGetMaximumPoolSize() { - ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(2, p2.getMaximumPoolSize()); - joinPool(p2); + ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + assertEquals(2, p.getMaximumPoolSize()); + joinPool(p); } /** - * getPoolSize increases, but doesn't overestimate, when threads - * become active + * getPoolSize increases, but doesn't overestimate, when threads + * become active */ - public void testGetPoolSize() { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p1.getPoolSize()); - p1.execute(new MediumRunnable()); - assertEquals(1, p1.getPoolSize()); - joinPool(p1); + public void testGetPoolSize() throws InterruptedException { + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + assertEquals(0, p.getPoolSize()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getPoolSize()); + done.await(); + }}); + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertEquals(1, p.getPoolSize()); + } finally { + done.countDown(); + joinPool(p); + } } /** - * getTaskCount increases, but doesn't overestimate, when tasks submitted + * getTaskCount increases, but doesn't overestimate, when tasks submitted */ public void testGetTaskCount() throws InterruptedException { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p1.getTaskCount()); - p1.execute(new MediumRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(1, p1.getTaskCount()); - joinPool(p1); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + assertEquals(0, p.getTaskCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getTaskCount()); + done.await(); + }}); + assertTrue(threadStarted.await(SMALL_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() { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p1.isShutdown()); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p1.isShutdown()); - joinPool(p1); + ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + assertFalse(p.isShutdown()); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.isShutdown()); + joinPool(p); } - /** - * isTerminated is false before termination, true after + * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p1.isTerminated()); - try { - p1.execute(new MediumRunnable()); - } finally { - try { p1.shutdown(); } catch (SecurityException ok) { return; } - } - assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p1.isTerminated()); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + assertFalse(p.isTerminating()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminating()); + threadStarted.countDown(); + done.await(); + }}); + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertFalse(p.isTerminating()); + done.countDown(); + } finally { + try { p.shutdown(); } catch (SecurityException ok) { return; } + } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertFalse(p.isTerminating()); } /** - * isTerminating is not true when running or when terminated + * isTerminating is not true when running or when terminated */ public void testIsTerminating() throws InterruptedException { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p1.isTerminating()); - try { - p1.execute(new SmallRunnable()); - assertFalse(p1.isTerminating()); - } finally { - try { p1.shutdown(); } catch (SecurityException ok) { return; } - } - assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p1.isTerminated()); - assertFalse(p1.isTerminating()); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + assertFalse(p.isTerminating()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminating()); + threadStarted.countDown(); + done.await(); + }}); + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertFalse(p.isTerminating()); + done.countDown(); + } finally { + try { p.shutdown(); } catch (SecurityException ok) { return; } + } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertFalse(p.isTerminating()); } /** * getQueue returns the work queue, which contains queued tasks */ public void testGetQueue() throws InterruptedException { - BlockingQueue q = new ArrayBlockingQueue(10); - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, q); - FutureTask[] tasks = new FutureTask[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE); - p1.execute(tasks[i]); - } - try { - Thread.sleep(SHORT_DELAY_MS); - BlockingQueue wq = p1.getQueue(); - assertSame(q, wq); - assertFalse(wq.contains(tasks[0])); - assertTrue(wq.contains(tasks[4])); - for (int i = 1; i < 5; ++i) - tasks[i].cancel(true); - p1.shutdownNow(); + final BlockingQueue q = new ArrayBlockingQueue(10); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + FutureTask[] tasks = new FutureTask[5]; + for (int i = 0; i < tasks.length; i++) { + Callable task = new CheckedCallable() { + public Boolean realCall() throws InterruptedException { + threadStarted.countDown(); + assertSame(q, p.getQueue()); + done.await(); + return Boolean.TRUE; + }}; + tasks[i] = new FutureTask(task); + p.execute(tasks[i]); + } + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertSame(q, p.getQueue()); + assertFalse(q.contains(tasks[0])); + assertTrue(q.contains(tasks[tasks.length - 1])); + assertEquals(tasks.length - 1, q.size()); } finally { - joinPool(p1); + done.countDown(); + joinPool(p); } } @@ -475,75 +650,128 @@ public class ThreadPoolExecutorSubclassT */ public void testRemove() throws InterruptedException { BlockingQueue q = new ArrayBlockingQueue(10); - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, q); - FutureTask[] tasks = new FutureTask[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE); - p1.execute(tasks[i]); - } - try { - Thread.sleep(SHORT_DELAY_MS); - assertFalse(p1.remove(tasks[0])); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); + Runnable[] tasks = new Runnable[6]; + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try { + for (int i = 0; i < tasks.length; i++) { + tasks[i] = new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + done.await(); + }}; + p.execute(tasks[i]); + } + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertFalse(p.remove(tasks[0])); assertTrue(q.contains(tasks[4])); assertTrue(q.contains(tasks[3])); - assertTrue(p1.remove(tasks[4])); - assertFalse(p1.remove(tasks[4])); + assertTrue(p.remove(tasks[4])); + assertFalse(p.remove(tasks[4])); assertFalse(q.contains(tasks[4])); assertTrue(q.contains(tasks[3])); - assertTrue(p1.remove(tasks[3])); + assertTrue(p.remove(tasks[3])); assertFalse(q.contains(tasks[3])); } finally { - joinPool(p1); + done.countDown(); + joinPool(p); } } /** - * purge removes cancelled tasks from the queue + * purge removes cancelled tasks from the queue */ - public void testPurge() { - ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + public void testPurge() throws InterruptedException { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + final BlockingQueue q = new ArrayBlockingQueue(10); + final ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); FutureTask[] tasks = new FutureTask[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE); - p1.execute(tasks[i]); + try { + for (int i = 0; i < tasks.length; i++) { + Callable task = new CheckedCallable() { + public Boolean realCall() throws InterruptedException { + threadStarted.countDown(); + done.await(); + return Boolean.TRUE; + }}; + tasks[i] = new FutureTask(task); + p.execute(tasks[i]); + } + assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + assertEquals(tasks.length, p.getTaskCount()); + assertEquals(tasks.length - 1, q.size()); + assertEquals(1L, p.getActiveCount()); + assertEquals(0L, p.getCompletedTaskCount()); + tasks[4].cancel(true); + tasks[3].cancel(false); + p.purge(); + assertEquals(tasks.length - 3, q.size()); + assertEquals(tasks.length - 2, p.getTaskCount()); + p.purge(); // Nothing to do + assertEquals(tasks.length - 3, q.size()); + assertEquals(tasks.length - 2, p.getTaskCount()); + } finally { + done.countDown(); + joinPool(p); } - tasks[4].cancel(true); - tasks[3].cancel(true); - p1.purge(); - long count = p1.getTaskCount(); - assertTrue(count >= 2 && count < 5); - joinPool(p1); } /** - * 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 p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List l; - try { - for (int i = 0; i < 5; i++) - p1.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 = p1.shutdownNow(); - } catch (SecurityException ok) { return; } - - } - assertTrue(p1.isShutdown()); - assertTrue(l.size() <= 4); + 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(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) {} } @@ -553,7 +781,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) {} } @@ -563,7 +792,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) {} } @@ -573,7 +803,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) {} } @@ -583,7 +814,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) {} } @@ -593,19 +825,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) {} } @@ -615,7 +847,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) {} } @@ -625,7 +859,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) {} } @@ -635,7 +871,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) {} } @@ -645,7 +883,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) {} } @@ -655,7 +895,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) {} } @@ -665,19 +905,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) {} } @@ -687,7 +929,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) {} } @@ -697,7 +941,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) {} } @@ -707,7 +953,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) {} } @@ -717,7 +965,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) {} } @@ -727,7 +977,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) {} } @@ -737,19 +989,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) {} } @@ -759,7 +1014,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) {} } @@ -769,7 +1027,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) {} } @@ -779,7 +1040,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) {} } @@ -789,80 +1053,101 @@ 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) {} } /** - * Constructor throws if workQueue is set to null + * Constructor throws if workQueue is null */ 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) {} } /** - * Constructor throws if handler is set to null + * Constructor throws if handler is null */ 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) {} } /** - * Constructor throws if ThreadFactory is set top null + * Constructor throws if ThreadFactory is null */ public void testConstructorNullPointerException8() { try { - ThreadFactory f = null; - new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),f,new NoOpREHandler()); + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10), + (ThreadFactory) null, + new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} } - /** - * execute throws RejectedExecutionException - * if saturated. + * execute throws RejectedExecutionException if saturated. */ public void testSaturatedExecute() { - ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1)); - try { - - for (int i = 0; i < 5; ++i) { - p.execute(new MediumRunnable()); + ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1)); + final CountDownLatch done = new CountDownLatch(1); + try { + Runnable task = new CheckedRunnable() { + public void realRun() throws InterruptedException { + done.await(); + }}; + for (int i = 0; i < 2; ++i) + p.execute(task); + for (int i = 0; i < 2; ++i) { + try { + p.execute(task); + shouldThrow(); + } catch (RejectedExecutionException success) {} + assertTrue(p.getTaskCount() <= 2); } - shouldThrow(); - } catch (RejectedExecutionException success) {} - joinPool(p); + } finally { + done.countDown(); + joinPool(p); + } } /** - * executor using CallerRunsPolicy runs task if saturated. + * executor using CallerRunsPolicy runs task if saturated. */ public void testSaturatedExecute2() { RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy(); - ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); + ThreadPoolExecutor p = new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + h); try { - TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5]; - for (int i = 0; i < 5; ++i) { + for (int i = 0; i < tasks.length; ++i) tasks[i] = new TrackedNoOpRunnable(); - } TrackedLongRunnable mr = new TrackedLongRunnable(); p.execute(mr); - for (int i = 0; i < 5; ++i) { + for (int i = 0; i < tasks.length; ++i) p.execute(tasks[i]); - } - for (int i = 1; i < 5; ++i) { + for (int i = 1; i < tasks.length; ++i) assertTrue(tasks[i].done); - } try { p.shutdownNow(); } catch (SecurityException ok) { return; } } finally { joinPool(p); @@ -870,24 +1155,24 @@ public class ThreadPoolExecutorSubclassT } /** - * executor using DiscardPolicy drops task if saturated. + * executor using DiscardPolicy drops task if saturated. */ public void testSaturatedExecute3() { RejectedExecutionHandler h = new CustomTPE.DiscardPolicy(); - ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); + ThreadPoolExecutor p = + new CustomTPE(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + h); try { - TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5]; - for (int i = 0; i < 5; ++i) { + for (int i = 0; i < tasks.length; ++i) tasks[i] = new TrackedNoOpRunnable(); - } p.execute(new TrackedLongRunnable()); - for (int i = 0; i < 5; ++i) { - p.execute(tasks[i]); - } - for (int i = 0; i < 5; ++i) { - assertFalse(tasks[i].done); - } + for (TrackedNoOpRunnable task : tasks) + p.execute(task); + for (TrackedNoOpRunnable task : tasks) + assertFalse(task.done); try { p.shutdownNow(); } catch (SecurityException ok) { return; } } finally { joinPool(p); @@ -895,7 +1180,7 @@ public class ThreadPoolExecutorSubclassT } /** - * executor using DiscardOldestPolicy drops oldest task if saturated. + * executor using DiscardOldestPolicy drops oldest task if saturated. */ public void testSaturatedExecute4() { RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy(); @@ -916,22 +1201,22 @@ public class ThreadPoolExecutorSubclassT } /** - * execute throws RejectedExecutionException if shutdown + * execute throws RejectedExecutionException if shutdown */ public void testRejectedExecutionExceptionOnShutdown() { - ThreadPoolExecutor tpe = + ThreadPoolExecutor p = new CustomTPE(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(1)); - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try { p.shutdown(); } catch (SecurityException ok) { return; } try { - tpe.execute(new NoOpRunnable()); + p.execute(new NoOpRunnable()); shouldThrow(); } catch (RejectedExecutionException success) {} - joinPool(tpe); + joinPool(p); } /** - * execute using CallerRunsPolicy drops task on shutdown + * execute using CallerRunsPolicy drops task on shutdown */ public void testCallerRunsOnShutdown() { RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy(); @@ -948,7 +1233,7 @@ public class ThreadPoolExecutorSubclassT } /** - * execute using DiscardPolicy drops task on shutdown + * execute using DiscardPolicy drops task on shutdown */ public void testDiscardOnShutdown() { RejectedExecutionHandler h = new CustomTPE.DiscardPolicy(); @@ -964,9 +1249,8 @@ public class ThreadPoolExecutorSubclassT } } - /** - * execute using DiscardOldestPolicy drops task on shutdown + * execute using DiscardOldestPolicy drops task on shutdown */ public void testDiscardOldestOnShutdown() { RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy(); @@ -982,115 +1266,117 @@ public class ThreadPoolExecutorSubclassT } } - /** - * execute (null) throws NPE + * execute(null) throws NPE */ public void testExecuteNull() { - ThreadPoolExecutor tpe = null; + ThreadPoolExecutor p = + new CustomTPE(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10)); try { - tpe = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); - tpe.execute(null); + p.execute(null); shouldThrow(); } catch (NullPointerException success) {} - joinPool(tpe); + joinPool(p); } /** - * setCorePoolSize of negative value throws IllegalArgumentException + * setCorePoolSize of negative value throws IllegalArgumentException */ public void testCorePoolSizeIllegalArgumentException() { - ThreadPoolExecutor tpe = + ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); try { - tpe.setCorePoolSize(-1); + p.setCorePoolSize(-1); shouldThrow(); } catch (IllegalArgumentException success) { } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try { p.shutdown(); } catch (SecurityException ok) { return; } } - joinPool(tpe); + joinPool(p); } /** - * setMaximumPoolSize(int) throws IllegalArgumentException if - * given a value less the core pool size + * setMaximumPoolSize(int) throws IllegalArgumentException + * if given a value less the core pool size */ public void testMaximumPoolSizeIllegalArgumentException() { - ThreadPoolExecutor tpe = + ThreadPoolExecutor p = new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); try { - tpe.setMaximumPoolSize(1); + p.setMaximumPoolSize(1); shouldThrow(); } catch (IllegalArgumentException success) { } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try { p.shutdown(); } catch (SecurityException ok) { return; } } - joinPool(tpe); + joinPool(p); } /** - * setMaximumPoolSize throws IllegalArgumentException - * if given a negative value + * setMaximumPoolSize throws IllegalArgumentException + * if given a negative value */ public void testMaximumPoolSizeIllegalArgumentException2() { - ThreadPoolExecutor tpe = + ThreadPoolExecutor p = new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); try { - tpe.setMaximumPoolSize(-1); + p.setMaximumPoolSize(-1); shouldThrow(); } catch (IllegalArgumentException success) { } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try { p.shutdown(); } catch (SecurityException ok) { return; } } - joinPool(tpe); + joinPool(p); } - /** - * setKeepAliveTime throws IllegalArgumentException - * when given a negative value + * setKeepAliveTime throws IllegalArgumentException + * when given a negative value */ public void testKeepAliveTimeIllegalArgumentException() { - ThreadPoolExecutor tpe = + ThreadPoolExecutor p = new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); try { - tpe.setKeepAliveTime(-1,MILLISECONDS); + p.setKeepAliveTime(-1,MILLISECONDS); shouldThrow(); } catch (IllegalArgumentException success) { } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try { p.shutdown(); } catch (SecurityException ok) { return; } } - joinPool(tpe); + joinPool(p); } /** * terminated() is called on termination */ public void testTerminated() { - CustomTPE tpe = new CustomTPE(); - try { tpe.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(tpe.terminatedCalled); - joinPool(tpe); + CustomTPE p = new CustomTPE(); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.terminatedCalled()); + joinPool(p); } /** * beforeExecute and afterExecute are called when executing task */ public void testBeforeAfter() throws InterruptedException { - CustomTPE tpe = new CustomTPE(); + CustomTPE p = new CustomTPE(); try { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - tpe.execute(r); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(r.done); - assertTrue(tpe.beforeCalled); - assertTrue(tpe.afterCalled); - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + 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(tpe); + joinPool(p); } } @@ -1136,7 +1422,6 @@ public class ThreadPoolExecutorSubclassT } } - /** * invokeAny(null) throws NPE */ @@ -1169,18 +1454,12 @@ public class ThreadPoolExecutorSubclassT * invokeAny(c) throws NPE if c has null elements */ public void testInvokeAny3() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); + CountDownLatch latch = new CountDownLatch(1); ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); try { - ArrayList> l = new ArrayList>(); - l.add(new Callable() { - public String call() { - try { - latch.await(); - } catch (InterruptedException ok) {} - return TEST_STRING; - }}); - l.add(null); e.invokeAny(l); shouldThrow(); } catch (NullPointerException success) { @@ -1195,9 +1474,9 @@ public class ThreadPoolExecutorSubclassT */ public void testInvokeAny4() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new NPETask()); try { - ArrayList> l = new ArrayList>(); - l.add(new NPETask()); e.invokeAny(l); shouldThrow(); } catch (ExecutionException success) { @@ -1213,7 +1492,7 @@ public class ThreadPoolExecutorSubclassT public void testInvokeAny5() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - ArrayList> l = new ArrayList>(); + List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -1255,10 +1534,10 @@ public class ThreadPoolExecutorSubclassT */ public void testInvokeAll3() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new StringTask()); + l.add(null); try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); e.invokeAll(l); shouldThrow(); } catch (NullPointerException success) { @@ -1272,13 +1551,12 @@ public class ThreadPoolExecutorSubclassT */ public void testInvokeAll4() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new NPETask()); + List> futures = e.invokeAll(l); + assertEquals(1, futures.size()); try { - ArrayList> l = new ArrayList>(); - l.add(new NPETask()); - List> result = e.invokeAll(l); - assertEquals(1, result.size()); - for (Future future : result) - future.get(); + futures.get(0).get(); shouldThrow(); } catch (ExecutionException success) { assertTrue(success.getCause() instanceof NullPointerException); @@ -1293,20 +1571,18 @@ public class ThreadPoolExecutorSubclassT public void testInvokeAll5() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - ArrayList> l = new ArrayList>(); + List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); - List> result = e.invokeAll(l); - assertEquals(2, result.size()); - for (Future future : result) + List> futures = e.invokeAll(l); + assertEquals(2, futures.size()); + for (Future future : futures) assertSame(TEST_STRING, future.get()); } finally { joinPool(e); } } - - /** * timed invokeAny(null) throws NPE */ @@ -1326,9 +1602,9 @@ public class ThreadPoolExecutorSubclassT */ public void testTimedInvokeAnyNullTimeUnit() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new StringTask()); try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); e.invokeAny(l, MEDIUM_DELAY_MS, null); shouldThrow(); } catch (NullPointerException success) { @@ -1355,18 +1631,12 @@ public class ThreadPoolExecutorSubclassT * timed invokeAny(c) throws NPE if c has null elements */ public void testTimedInvokeAny3() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); + CountDownLatch latch = new CountDownLatch(1); ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); try { - ArrayList> l = new ArrayList>(); - l.add(new Callable() { - public String call() { - try { - latch.await(); - } catch (InterruptedException ok) {} - return TEST_STRING; - }}); - l.add(null); e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (NullPointerException success) { @@ -1381,9 +1651,9 @@ public class ThreadPoolExecutorSubclassT */ public void testTimedInvokeAny4() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new NPETask()); try { - ArrayList> l = new ArrayList>(); - l.add(new NPETask()); e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (ExecutionException success) { @@ -1399,7 +1669,7 @@ public class ThreadPoolExecutorSubclassT public void testTimedInvokeAny5() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - ArrayList> l = new ArrayList>(); + List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); @@ -1428,9 +1698,9 @@ public class ThreadPoolExecutorSubclassT */ public void testTimedInvokeAllNullTimeUnit() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new StringTask()); try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); e.invokeAll(l, MEDIUM_DELAY_MS, null); shouldThrow(); } catch (NullPointerException success) { @@ -1457,10 +1727,10 @@ public class ThreadPoolExecutorSubclassT */ public void testTimedInvokeAll3() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new StringTask()); + l.add(null); try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (NullPointerException success) { @@ -1474,13 +1744,13 @@ public class ThreadPoolExecutorSubclassT */ public void testTimedInvokeAll4() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + List> l = new ArrayList>(); + l.add(new NPETask()); + List> futures = + e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + assertEquals(1, futures.size()); try { - ArrayList> l = new ArrayList>(); - l.add(new NPETask()); - List> result = e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); - assertEquals(1, result.size()); - for (Future future : result) - future.get(); + futures.get(0).get(); shouldThrow(); } catch (ExecutionException success) { assertTrue(success.getCause() instanceof NullPointerException); @@ -1495,12 +1765,13 @@ public class ThreadPoolExecutorSubclassT public void testTimedInvokeAll5() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - ArrayList> l = new ArrayList>(); + List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); - List> result = e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); - assertEquals(2, result.size()); - for (Future future : result) + List> futures = + e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); + assertEquals(2, futures.size()); + for (Future future : futures) assertSame(TEST_STRING, future.get()); } finally { joinPool(e); @@ -1513,21 +1784,29 @@ public class ThreadPoolExecutorSubclassT public void testTimedInvokeAll6() throws Exception { ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); - l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING)); - l.add(new StringTask()); - List> result = e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS); - assertEquals(3, result.size()); - Iterator> it = result.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); } @@ -1538,12 +1817,20 @@ public class ThreadPoolExecutorSubclassT * thread factory fails to create more */ public void testFailingThreadFactory() throws InterruptedException { - ExecutorService e = new CustomTPE(100, 100, LONG_DELAY_MS, MILLISECONDS, new LinkedBlockingQueue(), new FailingThreadFactory()); - try { - for (int k = 0; k < 100; ++k) { - e.execute(new NoOpRunnable()); - } - Thread.sleep(LONG_DELAY_MS); + final ExecutorService e = + new CustomTPE(100, 100, + LONG_DELAY_MS, MILLISECONDS, + new LinkedBlockingQueue(), + new FailingThreadFactory()); + try { + final int TASKS = 100; + final CountDownLatch done = new CountDownLatch(TASKS); + for (int k = 0; k < TASKS; ++k) + e.execute(new CheckedRunnable() { + public void realRun() { + done.countDown(); + }}); + assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); } finally { joinPool(e); } @@ -1553,38 +1840,103 @@ public class ThreadPoolExecutorSubclassT * allowsCoreThreadTimeOut is by default false. */ public void testAllowsCoreThreadTimeOut() { - ThreadPoolExecutor tpe = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(tpe.allowsCoreThreadTimeOut()); - joinPool(tpe); + ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); + assertFalse(p.allowsCoreThreadTimeOut()); + joinPool(p); } /** * allowCoreThreadTimeOut(true) causes idle threads to time out */ - public void testAllowCoreThreadTimeOut_true() throws InterruptedException { - ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue(10)); - tpe.allowCoreThreadTimeOut(true); - tpe.execute(new NoOpRunnable()); - try { - Thread.sleep(MEDIUM_DELAY_MS); - assertEquals(0, tpe.getPoolSize()); + public void testAllowCoreThreadTimeOut_true() throws Exception { + long keepAliveTime = timeoutMillis(); + final ThreadPoolExecutor p = + new CustomTPE(2, 10, + keepAliveTime, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + try { + p.allowCoreThreadTimeOut(true); + p.execute(new CheckedRunnable() { + public void realRun() { + threadStarted.countDown(); + assertEquals(1, p.getPoolSize()); + }}); + 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(tpe); + joinPool(p); } } /** * allowCoreThreadTimeOut(false) causes idle threads not to time out */ - public void testAllowCoreThreadTimeOut_false() throws InterruptedException { - ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue(10)); - tpe.allowCoreThreadTimeOut(false); - tpe.execute(new NoOpRunnable()); - try { - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(tpe.getPoolSize() >= 1); + public void testAllowCoreThreadTimeOut_false() throws Exception { + long keepAliveTime = timeoutMillis(); + final ThreadPoolExecutor p = + new CustomTPE(2, 10, + keepAliveTime, MILLISECONDS, + new ArrayBlockingQueue(10)); + final CountDownLatch threadStarted = new CountDownLatch(1); + try { + p.allowCoreThreadTimeOut(false); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertTrue(p.getPoolSize() >= 1); + }}); + 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(tpe); + joinPool(e); } }