--- jsr166/src/test/tck/ThreadPoolExecutorTest.java 2010/10/09 19:30:35 1.35 +++ jsr166/src/test/tck/ThreadPoolExecutorTest.java 2015/10/06 05:30:44 1.108 @@ -1,40 +1,73 @@ /* * 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.atomic.*; -import junit.framework.*; -import java.util.*; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +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.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import junit.framework.Test; +import junit.framework.TestSuite; public class ThreadPoolExecutorTest extends JSR166TestCase { public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); + main(suite(), args); } public static Test suite() { return new TestSuite(ThreadPoolExecutorTest.class); } static class ExtendedTPE extends ThreadPoolExecutor { - 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 ExtendedTPE() { 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; } } @@ -46,17 +79,20 @@ public class ThreadPoolExecutorTest exte } } - /** * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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 ThreadPoolExecutor(1, 1, + 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)); } } @@ -65,40 +101,72 @@ public class ThreadPoolExecutorTest exte * thread becomes active */ public void testGetActiveCount() throws InterruptedException { - ThreadPoolExecutor p2 = new ThreadPoolExecutor(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 ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + 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 { + threadStarted.countDown(); + assertEquals(1, p.getActiveCount()); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getActiveCount()); + done.countDown(); + } } /** * prestartCoreThread starts a thread if under corePoolSize, else doesn't */ public void testPrestartCoreThread() { - ThreadPoolExecutor p2 = new ThreadPoolExecutor(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); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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 p2 = new ThreadPoolExecutor(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); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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()); + } } /** @@ -106,67 +174,105 @@ public class ThreadPoolExecutorTest exte * when tasks complete */ public void testGetCompletedTaskCount() throws InterruptedException { - ThreadPoolExecutor p2 = new ThreadPoolExecutor(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 ThreadPoolExecutor(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 */ public void testGetCorePoolSize() { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p1.getCorePoolSize()); - joinPool(p1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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 p2 = new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS)); - joinPool(p2); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10), tf, new NoOpREHandler()); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + ThreadFactory threadFactory = new SimpleThreadFactory(); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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 ThreadPoolExecutor(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 ThreadPoolExecutor(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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setThreadFactory(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setThreadFactory(null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -174,10 +280,15 @@ public class ThreadPoolExecutorTest exte * getRejectedExecutionHandler returns handler in constructor if not set */ public void testGetRejectedExecutionHandler() { - RejectedExecutionHandler h = new NoOpREHandler(); - ThreadPoolExecutor p = new ThreadPoolExecutor(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 ThreadPoolExecutor(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10), + handler); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(handler, p.getRejectedExecutionHandler()); + } } /** @@ -185,41 +296,58 @@ public class ThreadPoolExecutorTest exte * getRejectedExecutionHandler */ public void testSetRejectedExecutionHandler() { - ThreadPoolExecutor p = new ThreadPoolExecutor(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 ThreadPoolExecutor(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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setRejectedExecutionHandler(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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 */ public void testGetLargestPoolSize() throws InterruptedException { - ThreadPoolExecutor p2 = new ThreadPoolExecutor(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 CountDownLatch done = new CountDownLatch(1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(THREADS, THREADS, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p, done)) { + assertEquals(0, p.getLargestPoolSize()); + final CountDownLatch threadsStarted = new CountDownLatch(THREADS); + for (int i = 0; i < THREADS; i++) + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadsStarted.countDown(); + await(done); + assertEquals(THREADS, p.getLargestPoolSize()); + }}); + await(threadsStarted); + assertEquals(THREADS, p.getLargestPoolSize()); + } + assertEquals(THREADS, p.getLargestPoolSize()); } /** @@ -227,102 +355,214 @@ public class ThreadPoolExecutorTest exte * otherwise set */ public void testGetMaximumPoolSize() { - ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(2, p2.getMaximumPoolSize()); - joinPool(p2); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(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()); + } } /** * getPoolSize increases, but doesn't overestimate, when threads * become active */ - public void testGetPoolSize() { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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 CountDownLatch done = new CountDownLatch(1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p, done)) { + assertEquals(0, p.getPoolSize()); + final CountDownLatch threadStarted = new CountDownLatch(1); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getPoolSize()); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getPoolSize()); + } } /** * getTaskCount increases, but doesn't overestimate, when tasks submitted */ public void testGetTaskCount() throws InterruptedException { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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 int TASKS = 3; + final CountDownLatch done = new CountDownLatch(1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + assertEquals(0, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + for (int i = 0; i < TASKS; i++) { + assertEquals(1 + i, p.getTaskCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1 + TASKS, p.getTaskCount()); + await(done); + }}); + } + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + } + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(1 + TASKS, p.getCompletedTaskCount()); } /** - * isShutDown is false before shutdown, true after + * isShutdown is false before shutdown, true after */ public void testIsShutdown() { - - ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p1.isShutdown()); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p1.isShutdown()); - joinPool(p1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.isShutdown()); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.isShutdown()); + } } + /** + * awaitTermination on a non-shutdown pool times out + */ + public void testAwaitTermination_timesOut() throws InterruptedException { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.isTerminated()); + assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS)); + assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS)); + assertFalse(p.awaitTermination(-1L, NANOSECONDS)); + assertFalse(p.awaitTermination(-1L, MILLISECONDS)); + assertFalse(p.awaitTermination(0L, NANOSECONDS)); + assertFalse(p.awaitTermination(0L, MILLISECONDS)); + long timeoutNanos = 999999L; + long startTime = System.nanoTime(); + assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS)); + assertTrue(System.nanoTime() - startTime >= timeoutNanos); + assertFalse(p.isTerminated()); + startTime = System.nanoTime(); + long timeoutMillis = timeoutMillis(); + assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS)); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + assertFalse(p.isTerminated()); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + } + } /** * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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; } + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + assertFalse(p.isTerminating()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminating()); + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertFalse(p.isTerminating()); + done.countDown(); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertFalse(p.isTerminating()); } - assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p1.isTerminated()); } /** * isTerminating is not true when running or when terminated */ public void testIsTerminating() throws InterruptedException { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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 ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + assertFalse(p.isTerminating()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminating()); + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertFalse(p.isTerminating()); + done.countDown(); + 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 ThreadPoolExecutor(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(); - } finally { - joinPool(p1); + final BlockingQueue q = new ArrayBlockingQueue(10); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + 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()); + await(done); + return Boolean.TRUE; + }}; + tasks[i] = new FutureTask(task); + p.execute(tasks[i]); + } + await(threadStarted); + assertSame(q, p.getQueue()); + assertFalse(q.contains(tasks[0])); + assertTrue(q.contains(tasks[tasks.length - 1])); + assertEquals(tasks.length - 1, q.size()); + done.countDown(); } } @@ -331,74 +571,124 @@ public class ThreadPoolExecutorTest exte */ public void testRemove() throws InterruptedException { BlockingQueue q = new ArrayBlockingQueue(10); - ThreadPoolExecutor p1 = new ThreadPoolExecutor(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 ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); + try (PoolCleaner cleaner = cleaner(p)) { + Runnable[] tasks = new Runnable[6]; + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + for (int i = 0; i < tasks.length; i++) { + tasks[i] = new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + await(done); + }}; + p.execute(tasks[i]); + } + await(threadStarted); + 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(); } } /** * purge removes cancelled tasks from the queue */ - public void testPurge() { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - FutureTask[] tasks = new FutureTask[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE); - p1.execute(tasks[i]); + 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 ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + q); + try (PoolCleaner cleaner = cleaner(p, done)) { + FutureTask[] tasks = new FutureTask[5]; + for (int i = 0; i < tasks.length; i++) { + Callable task = new CheckedCallable() { + public Boolean realCall() throws InterruptedException { + threadStarted.countDown(); + await(done); + return Boolean.TRUE; + }}; + tasks[i] = new FutureTask(task); + p.execute(tasks[i]); + } + await(threadStarted); + 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()); } - 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 - */ - public void testShutDownNow() { - ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List l; - try { - for (int i = 0; i < 5; i++) - p1.execute(new MediumPossiblyInterruptedRunnable()); - } - finally { + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue + */ + public void testShutdownNow() throws InterruptedException { + final int poolSize = 2; + final int count = 5; + final AtomicInteger ran = new AtomicInteger(0); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(poolSize, poolSize, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + final 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); + await(threadsStarted); + 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 ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new ThreadPoolExecutor(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -408,7 +698,8 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor2() { try { - new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new ThreadPoolExecutor(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -418,7 +709,8 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor3() { try { - new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new ThreadPoolExecutor(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -428,7 +720,8 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor4() { try { - new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10)); + new ThreadPoolExecutor(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -438,7 +731,8 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor5() { try { - new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + new ThreadPoolExecutor(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10)); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -448,19 +742,20 @@ public class ThreadPoolExecutorTest exte */ public void testConstructorNullPointerException() { try { - new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null); + new ThreadPoolExecutor(1, 2, 1L, SECONDS, + (BlockingQueue) null); shouldThrow(); } catch (NullPointerException success) {} } - - /** * Constructor throws if corePoolSize argument is less than zero */ public void testConstructor6() { try { - new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new ThreadPoolExecutor(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -470,7 +765,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor7() { try { - new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new ThreadPoolExecutor(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -480,7 +777,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor8() { try { - new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new ThreadPoolExecutor(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -490,7 +789,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor9() { try { - new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new ThreadPoolExecutor(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -500,7 +801,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor10() { try { - new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory()); + new ThreadPoolExecutor(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -510,7 +813,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructorNullPointerException2() { try { - new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory()); + new ThreadPoolExecutor(1, 2, 1L, SECONDS, + (BlockingQueue) null, + new SimpleThreadFactory()); shouldThrow(); } catch (NullPointerException success) {} } @@ -520,19 +825,21 @@ public class ThreadPoolExecutorTest exte */ public void testConstructorNullPointerException3() { try { - ThreadFactory f = null; - new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),f); + new ThreadPoolExecutor(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 ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new ThreadPoolExecutor(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -542,7 +849,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor12() { try { - new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new ThreadPoolExecutor(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -552,7 +861,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor13() { try { - new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new ThreadPoolExecutor(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -562,7 +873,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor14() { try { - new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new ThreadPoolExecutor(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -572,7 +885,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor15() { try { - new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new NoOpREHandler()); + new ThreadPoolExecutor(2, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -582,7 +897,9 @@ public class ThreadPoolExecutorTest exte */ public void testConstructorNullPointerException4() { try { - new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new NoOpREHandler()); + new ThreadPoolExecutor(1, 2, 1L, SECONDS, + (BlockingQueue) null, + new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} } @@ -592,19 +909,22 @@ public class ThreadPoolExecutorTest exte */ public void testConstructorNullPointerException5() { try { - RejectedExecutionHandler r = null; - new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),r); + new ThreadPoolExecutor(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 ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(-1, 1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -614,7 +934,10 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor17() { try { - new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(1, -1, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -624,7 +947,10 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor18() { try { - new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(1, 0, 1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -634,7 +960,10 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor19() { try { - new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(1, 2, -1L, SECONDS, + new ArrayBlockingQueue(10), + new SimpleThreadFactory(), + new NoOpREHandler()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -644,63 +973,160 @@ public class ThreadPoolExecutorTest exte */ public void testConstructor20() { try { - new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10),new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler()); + new ThreadPoolExecutor(1, 2, 1L, SECONDS, + (BlockingQueue) 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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),new SimpleThreadFactory(),r); + new ThreadPoolExecutor(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 ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10),f,new NoOpREHandler()); + new ThreadPoolExecutor(1, 2, 1L, SECONDS, + new ArrayBlockingQueue(10), + (ThreadFactory) null, + new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} } + /** + * get of submitted callable throws InterruptedException if interrupted + */ + public void testInterruptedSubmit() throws InterruptedException { + final CountDownLatch done = new CountDownLatch(1); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + 60, SECONDS, + new ArrayBlockingQueue(10)); + + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + Thread t = newStartedThread(new CheckedInterruptedRunnable() { + public void realRun() throws Exception { + Callable task = new CheckedCallable() { + public Boolean realCall() throws InterruptedException { + threadStarted.countDown(); + await(done); + return Boolean.TRUE; + }}; + p.submit(task).get(); + }}); + + await(threadStarted); + t.interrupt(); + awaitTermination(t); + } + } /** * execute throws RejectedExecutionException if saturated. */ public void testSaturatedExecute() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1)); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() throws InterruptedException { + await(done); + }}; + 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); + } + done.countDown(); + } + } + + /** + * submit(runnable) throws RejectedExecutionException if saturated. + */ + public void testSaturatedSubmitRunnable() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() throws InterruptedException { + await(done); + }}; for (int i = 0; i < 2; ++i) - p.execute(new MediumRunnable()); + p.submit(task); for (int i = 0; i < 2; ++i) { try { - p.execute(new MediumRunnable()); + p.execute(task); shouldThrow(); } catch (RejectedExecutionException success) {} + assertTrue(p.getTaskCount() <= 2); } - } finally { - joinPool(p); + done.countDown(); + } + } + + /** + * submit(callable) throws RejectedExecutionException if saturated. + */ + public void testSaturatedSubmitCallable() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() throws InterruptedException { + await(done); + }}; + for (int i = 0; i < 2; ++i) + p.submit(Executors.callable(task)); + for (int i = 0; i < 2; ++i) { + try { + p.execute(task); + shouldThrow(); + } catch (RejectedExecutionException success) {} + assertTrue(p.getTaskCount() <= 2); + } + done.countDown(); } } @@ -708,25 +1134,28 @@ public class ThreadPoolExecutorTest exte * executor using CallerRunsPolicy runs task if saturated. */ public void testSaturatedExecute2() { - RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); - try { - + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, + MILLISECONDS, + new ArrayBlockingQueue(1), + new ThreadPoolExecutor.CallerRunsPolicy()); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + Runnable blocker = new CheckedRunnable() { + public void realRun() throws InterruptedException { + await(done); + }}; + p.execute(blocker); 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); + assertFalse(tasks[0].done); // waiting in queue + done.countDown(); } } @@ -734,61 +1163,74 @@ public class ThreadPoolExecutorTest exte * executor using DiscardPolicy drops task if saturated. */ public void testSaturatedExecute3() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); - try { - - TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5]; - for (int i = 0; i < 5; ++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) { + final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5]; + for (int i = 0; i < tasks.length; ++i) + tasks[i] = new TrackedNoOpRunnable(); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + new ThreadPoolExecutor.DiscardPolicy()); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + p.execute(awaiter(done)); + + for (TrackedNoOpRunnable task : tasks) + p.execute(task); + for (int i = 1; i < tasks.length; i++) assertFalse(tasks[i].done); - } - try { p.shutdownNow(); } catch (SecurityException ok) { return; } - } finally { - joinPool(p); + done.countDown(); } + for (int i = 1; i < tasks.length; i++) + assertFalse(tasks[i].done); + assertTrue(tasks[0].done); // was waiting in queue } /** * executor using DiscardOldestPolicy drops oldest task if saturated. */ public void testSaturatedExecute4() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); - try { - p.execute(new TrackedLongRunnable()); - TrackedLongRunnable r2 = new TrackedLongRunnable(); + final CountDownLatch done = new CountDownLatch(1); + LatchAwaiter r1 = awaiter(done); + LatchAwaiter r2 = awaiter(done); + LatchAwaiter r3 = awaiter(done); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + new ThreadPoolExecutor.DiscardOldestPolicy()); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(LatchAwaiter.NEW, r1.state); + assertEquals(LatchAwaiter.NEW, r2.state); + assertEquals(LatchAwaiter.NEW, r3.state); + p.execute(r1); p.execute(r2); assertTrue(p.getQueue().contains(r2)); - TrackedNoOpRunnable r3 = new TrackedNoOpRunnable(); p.execute(r3); assertFalse(p.getQueue().contains(r2)); assertTrue(p.getQueue().contains(r3)); - try { p.shutdownNow(); } catch (SecurityException ok) { return; } - } finally { - joinPool(p); + done.countDown(); } + assertEquals(LatchAwaiter.DONE, r1.state); + assertEquals(LatchAwaiter.NEW, r2.state); + assertEquals(LatchAwaiter.DONE, r3.state); } /** * execute throws RejectedExecutionException if shutdown */ public void testRejectedExecutionExceptionOnShutdown() { - ThreadPoolExecutor tpe = - new ThreadPoolExecutor(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(1)); - try { tpe.shutdown(); } catch (SecurityException ok) { return; } - try { - tpe.execute(new NoOpRunnable()); - shouldThrow(); - } catch (RejectedExecutionException success) {} - - joinPool(tpe); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1)); + try { p.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.execute(new NoOpRunnable()); + shouldThrow(); + } catch (RejectedExecutionException success) {} + } } /** @@ -796,15 +1238,16 @@ public class ThreadPoolExecutorTest exte */ public void testCallerRunsOnShutdown() { RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), h); try { p.shutdown(); } catch (SecurityException ok) { return; } - try { + try (PoolCleaner cleaner = cleaner(p)) { TrackedNoOpRunnable r = new TrackedNoOpRunnable(); p.execute(r); assertFalse(r.done); - } finally { - joinPool(p); } } @@ -812,67 +1255,68 @@ public class ThreadPoolExecutorTest exte * execute using DiscardPolicy drops task on shutdown */ public void testDiscardOnShutdown() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + new ThreadPoolExecutor.DiscardPolicy()); try { p.shutdown(); } catch (SecurityException ok) { return; } - try { + try (PoolCleaner cleaner = cleaner(p)) { TrackedNoOpRunnable r = new TrackedNoOpRunnable(); p.execute(r); assertFalse(r.done); - } finally { - joinPool(p); } } - /** * execute using DiscardOldestPolicy drops task on shutdown */ public void testDiscardOldestOnShutdown() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy(); - ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), h); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(1), + new ThreadPoolExecutor.DiscardOldestPolicy()); try { p.shutdown(); } catch (SecurityException ok) { return; } - try { + try (PoolCleaner cleaner = cleaner(p)) { TrackedNoOpRunnable r = new TrackedNoOpRunnable(); p.execute(r); assertFalse(r.done); - } finally { - joinPool(p); } } - /** * execute(null) throws NPE */ public void testExecuteNull() { - ThreadPoolExecutor tpe = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue(10)); - try { - tpe.execute(null); - shouldThrow(); - } catch (NullPointerException success) {} - - joinPool(tpe); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 2, + 1L, SECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.execute(null); + shouldThrow(); + } catch (NullPointerException success) {} + } } /** * setCorePoolSize of negative value throws IllegalArgumentException */ public void testCorePoolSizeIllegalArgumentException() { - ThreadPoolExecutor tpe = + final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - tpe.setCorePoolSize(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setCorePoolSize(-1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(tpe); } /** @@ -880,18 +1324,16 @@ public class ThreadPoolExecutorTest exte * given a value less the core pool size */ public void testMaximumPoolSizeIllegalArgumentException() { - ThreadPoolExecutor tpe = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - tpe.setMaximumPoolSize(1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setMaximumPoolSize(1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(tpe); } /** @@ -899,65 +1341,91 @@ public class ThreadPoolExecutorTest exte * if given a negative value */ public void testMaximumPoolSizeIllegalArgumentException2() { - ThreadPoolExecutor tpe = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - tpe.setMaximumPoolSize(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setMaximumPoolSize(-1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(tpe); } + /** + * Configuration changes that allow core pool size greater than + * max pool size result in IllegalArgumentException. + */ + public void testPoolSizeInvariants() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + for (int s = 1; s < 5; s++) { + p.setMaximumPoolSize(s); + p.setCorePoolSize(s); + try { + p.setMaximumPoolSize(s - 1); + shouldThrow(); + } catch (IllegalArgumentException success) {} + assertEquals(s, p.getCorePoolSize()); + assertEquals(s, p.getMaximumPoolSize()); + try { + p.setCorePoolSize(s + 1); + shouldThrow(); + } catch (IllegalArgumentException success) {} + assertEquals(s, p.getCorePoolSize()); + assertEquals(s, p.getMaximumPoolSize()); + } + } + } /** * setKeepAliveTime throws IllegalArgumentException * when given a negative value */ public void testKeepAliveTimeIllegalArgumentException() { - ThreadPoolExecutor tpe = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - tpe.setKeepAliveTime(-1,MILLISECONDS); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { tpe.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setKeepAliveTime(-1, MILLISECONDS); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(tpe); } /** * terminated() is called on termination */ public void testTerminated() { - ExtendedTPE tpe = new ExtendedTPE(); - try { tpe.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(tpe.terminatedCalled); - joinPool(tpe); + ExtendedTPE p = new ExtendedTPE(); + try (PoolCleaner cleaner = cleaner(p)) { + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.terminatedCalled()); + assertTrue(p.isShutdown()); + } } /** * beforeExecute and afterExecute are called when executing task */ public void testBeforeAfter() throws InterruptedException { - ExtendedTPE tpe = new ExtendedTPE(); - 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; } - } finally { - joinPool(tpe); + ExtendedTPE p = new ExtendedTPE(); + try (PoolCleaner cleaner = cleaner(p)) { + 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()); } } @@ -965,13 +1433,14 @@ public class ThreadPoolExecutorTest exte * completed submit of callable returns result */ public void testSubmitCallable() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new StringTask()); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -979,13 +1448,14 @@ public class ThreadPoolExecutorTest exte * completed submit of runnable returns successfully */ public void testSubmitRunnable() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable()); future.get(); assertTrue(future.isDone()); - } finally { - joinPool(e); } } @@ -993,28 +1463,30 @@ public class ThreadPoolExecutorTest exte * completed submit of (runnable, result) returns result */ public void testSubmitRunnable2() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable(), TEST_STRING); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } - /** * invokeAny(null) throws NPE */ public void testInvokeAny1() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAny(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1022,13 +1494,15 @@ public class ThreadPoolExecutorTest exte * invokeAny(empty collection) throws IAE */ public void testInvokeAny2() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAny(new ArrayList>()); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } @@ -1036,18 +1510,20 @@ public class ThreadPoolExecutorTest exte * invokeAny(c) throws NPE if c has null elements */ public void testInvokeAny3() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(latchAwaitingStringTask(latch)); - l.add(null); - try { - e.invokeAny(l); - shouldThrow(); - } catch (NullPointerException success) { - } finally { + final CountDownLatch latch = new CountDownLatch(1); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); + try { + e.invokeAny(l); + shouldThrow(); + } catch (NullPointerException success) {} latch.countDown(); - joinPool(e); } } @@ -1055,16 +1531,19 @@ public class ThreadPoolExecutorTest exte * invokeAny(c) throws ExecutionException if no task completes */ public void testInvokeAny4() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new NPETask()); - try { - e.invokeAny(l); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new NPETask()); + try { + e.invokeAny(l); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } } @@ -1072,15 +1551,16 @@ public class ThreadPoolExecutorTest exte * invokeAny(c) returns result of some task */ public void testInvokeAny5() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -1088,13 +1568,15 @@ public class ThreadPoolExecutorTest exte * invokeAll(null) throws NPE */ public void testInvokeAll1() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAll(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1102,12 +1584,13 @@ public class ThreadPoolExecutorTest exte * invokeAll(empty collection) returns empty collection */ public void testInvokeAll2() throws InterruptedException { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> r = e.invokeAll(new ArrayList>()); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -1115,16 +1598,18 @@ public class ThreadPoolExecutorTest exte * invokeAll(c) throws NPE if c has null elements */ public void testInvokeAll3() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); - try { - e.invokeAll(l); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new StringTask()); + l.add(null); + try { + e.invokeAll(l); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1132,8 +1617,11 @@ public class ThreadPoolExecutorTest exte * get of element of invokeAll(c) throws exception on failed task */ public void testInvokeAll4() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); l.add(new NPETask()); List> futures = e.invokeAll(l); @@ -1144,8 +1632,6 @@ public class ThreadPoolExecutorTest exte } catch (ExecutionException success) { assertTrue(success.getCause() instanceof NullPointerException); } - } finally { - joinPool(e); } } @@ -1153,8 +1639,11 @@ public class ThreadPoolExecutorTest exte * invokeAll(c) returns results of all completed tasks */ public void testInvokeAll5() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); @@ -1162,24 +1651,22 @@ public class ThreadPoolExecutorTest exte assertEquals(2, futures.size()); for (Future future : futures) assertSame(TEST_STRING, future.get()); - } finally { - joinPool(e); } } - - /** * timed invokeAny(null) throws NPE */ public void testTimedInvokeAny1() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1187,15 +1674,17 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(,,null) throws NPE */ public void testTimedInvokeAnyNullTimeUnit() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new StringTask()); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new StringTask()); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1203,13 +1692,16 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(empty collection) throws IAE */ public void testTimedInvokeAny2() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAny(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>(), + MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } @@ -1217,18 +1709,20 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(c) throws NPE if c has null elements */ public void testTimedInvokeAny3() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(latchAwaitingStringTask(latch)); - l.add(null); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { + final CountDownLatch latch = new CountDownLatch(1); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} latch.countDown(); - joinPool(e); } } @@ -1236,16 +1730,19 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(c) throws ExecutionException if no task completes */ public void testTimedInvokeAny4() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new NPETask()); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new NPETask()); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } } @@ -1253,15 +1750,16 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(c) returns result of some task */ public void testTimedInvokeAny5() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -1269,13 +1767,15 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(null) throws NPE */ public void testTimedInvokeAll1() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1283,15 +1783,17 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(,,null) throws NPE */ public void testTimedInvokeAllNullTimeUnit() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new StringTask()); - try { - e.invokeAll(l, MEDIUM_DELAY_MS, null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new StringTask()); + try { + e.invokeAll(l, MEDIUM_DELAY_MS, null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1299,12 +1801,14 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(empty collection) returns empty collection */ public void testTimedInvokeAll2() throws InterruptedException { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> r = e.invokeAll(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(new ArrayList>(), + MEDIUM_DELAY_MS, MILLISECONDS); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -1312,16 +1816,18 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) throws NPE if c has null elements */ public void testTimedInvokeAll3() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); - try { - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new StringTask()); + l.add(null); + try { + e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1329,19 +1835,22 @@ public class ThreadPoolExecutorTest exte * get of element of invokeAll(c) throws exception on failed task */ public void testTimedInvokeAll4() throws Exception { - ExecutorService e = new ThreadPoolExecutor(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 { - futures.get(0).get(); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(new NPETask()); + List> futures = + e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); + assertEquals(1, futures.size()); + try { + futures.get(0).get(); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } } @@ -1349,18 +1858,19 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) returns results of all completed tasks */ public void testTimedInvokeAll5() throws Exception { - ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); 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()); - } finally { - joinPool(e); } } @@ -1368,26 +1878,34 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) cancels tasks not completed by timeout */ public void testTimedInvokeAll6() throws Exception { - ExecutorService e = new ThreadPoolExecutor(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()); - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(e)) { + 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"); + } + } } } @@ -1396,15 +1914,20 @@ public class ThreadPoolExecutorTest exte * thread factory fails to create more */ public void testFailingThreadFactory() throws InterruptedException { - ExecutorService e = new ThreadPoolExecutor(100, 100, LONG_DELAY_MS, MILLISECONDS, new LinkedBlockingQueue(), new FailingThreadFactory()); - try { - List> l = new ArrayList>(); - for (int k = 0; k < 100; ++k) { - e.execute(new NoOpRunnable()); - } - Thread.sleep(LONG_DELAY_MS); - } finally { - joinPool(e); + final ExecutorService e = + new ThreadPoolExecutor(100, 100, + LONG_DELAY_MS, MILLISECONDS, + new LinkedBlockingQueue(), + new FailingThreadFactory()); + try (PoolCleaner cleaner = cleaner(e)) { + 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)); } } @@ -1412,38 +1935,62 @@ public class ThreadPoolExecutorTest exte * allowsCoreThreadTimeOut is by default false. */ public void testAllowsCoreThreadTimeOut() { - ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(tpe.allowsCoreThreadTimeOut()); - joinPool(tpe); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(2, 2, + 1000, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.allowsCoreThreadTimeOut()); + } } /** * allowCoreThreadTimeOut(true) causes idle threads to time out */ - public void testAllowCoreThreadTimeOut_true() throws InterruptedException { - ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue(10)); - tpe.allowCoreThreadTimeOut(true); - tpe.execute(new NoOpRunnable()); - try { - Thread.sleep(MEDIUM_DELAY_MS); - assertEquals(0, tpe.getPoolSize()); - } finally { - joinPool(tpe); + public void testAllowCoreThreadTimeOut_true() throws Exception { + long keepAliveTime = timeoutMillis(); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(2, 10, + keepAliveTime, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + 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()); } } /** * allowCoreThreadTimeOut(false) causes idle threads not to time out */ - public void testAllowCoreThreadTimeOut_false() throws InterruptedException { - ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue(10)); - tpe.allowCoreThreadTimeOut(false); - tpe.execute(new NoOpRunnable()); - try { - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(tpe.getPoolSize() >= 1); - } finally { - joinPool(tpe); + public void testAllowCoreThreadTimeOut_false() throws Exception { + long keepAliveTime = timeoutMillis(); + final ThreadPoolExecutor p = + new ThreadPoolExecutor(2, 10, + keepAliveTime, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + 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); } } @@ -1453,29 +2000,65 @@ public class ThreadPoolExecutorTest exte */ public void testRejectedRecycledTask() throws InterruptedException { final int nTasks = 1000; - final AtomicInteger nRun = new AtomicInteger(0); + final CountDownLatch done = new CountDownLatch(nTasks); final Runnable recycledTask = new Runnable() { - public void run() { - nRun.getAndIncrement(); - } }; + public void run() { + done.countDown(); + }}; final ThreadPoolExecutor p = - new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS, + new ThreadPoolExecutor(1, 30, + 60, SECONDS, new ArrayBlockingQueue(30)); - try { + try (PoolCleaner cleaner = cleaner(p)) { for (int i = 0; i < nTasks; ++i) { for (;;) { try { p.execute(recycledTask); break; } - catch (RejectedExecutionException ignore) { - } + catch (RejectedExecutionException ignore) {} } } - Thread.sleep(5000); // enough time to run all tasks - assertEquals(nRun.get(), nTasks); - } finally { - p.shutdown(); + // enough time to run all tasks + assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS)); + } + } + + /** + * get(cancelled task) throws CancellationException + */ + public void testGet_cancelled() throws Exception { + final ExecutorService e = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new LinkedBlockingQueue()); + try (PoolCleaner cleaner = cleaner(e)) { + 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)); + } + await(blockerStarted); + 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(); } }