--- jsr166/src/test/tck/ThreadPoolExecutorTest.java 2015/09/28 03:05:23 1.62 +++ jsr166/src/test/tck/ThreadPoolExecutorTest.java 2021/01/26 13:33:06 1.127 @@ -11,6 +11,8 @@ import static java.util.concurrent.TimeU import static java.util.concurrent.TimeUnit.SECONDS; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -18,7 +20,6 @@ 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; @@ -27,9 +28,14 @@ import java.util.concurrent.RejectedExec import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; +import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; +import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; +import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import junit.framework.Test; import junit.framework.TestSuite; @@ -87,16 +93,12 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch done = new CountDownLatch(1); - final Runnable task = new CheckedRunnable() { - public void realRun() { - done.countDown(); - }}; - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + final Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; p.execute(task); - assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS)); - } finally { - joinPool(p); + await(done); } } @@ -105,25 +107,22 @@ public class ThreadPoolExecutorTest exte * thread becomes active */ public void testGetActiveCount() throws InterruptedException { + final CountDownLatch done = new CountDownLatch(1); final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); assertEquals(0, p.getActiveCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); assertEquals(1, p.getActiveCount()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getActiveCount()); - } finally { - done.countDown(); - joinPool(p); } } @@ -132,17 +131,25 @@ public class ThreadPoolExecutorTest exte */ public void testPrestartCoreThread() { final ThreadPoolExecutor p = - new ThreadPoolExecutor(2, 2, + new ThreadPoolExecutor(2, 6, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p.getPoolSize()); - assertTrue(p.prestartCoreThread()); - assertEquals(1, p.getPoolSize()); - assertTrue(p.prestartCoreThread()); - assertEquals(2, p.getPoolSize()); - assertFalse(p.prestartCoreThread()); - assertEquals(2, p.getPoolSize()); - joinPool(p); + 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()); + } } /** @@ -150,15 +157,21 @@ public class ThreadPoolExecutorTest exte */ public void testPrestartAllCoreThreads() { final ThreadPoolExecutor p = - new ThreadPoolExecutor(2, 2, + new ThreadPoolExecutor(2, 6, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(0, p.getPoolSize()); - p.prestartAllCoreThreads(); - assertEquals(2, p.getPoolSize()); - p.prestartAllCoreThreads(); - assertEquals(2, p.getPoolSize()); - joinPool(p); + 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()); + } } /** @@ -170,30 +183,28 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch threadProceed = new CountDownLatch(1); - final CountDownLatch threadDone = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch threadProceed = new CountDownLatch(1); + final CountDownLatch threadDone = new CountDownLatch(1); assertEquals(0, p.getCompletedTaskCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); assertEquals(0, p.getCompletedTaskCount()); - threadProceed.await(); + await(threadProceed); threadDone.countDown(); }}); await(threadStarted); assertEquals(0, p.getCompletedTaskCount()); threadProceed.countDown(); - threadDone.await(); + await(threadDone); long startTime = System.nanoTime(); while (p.getCompletedTaskCount() != 1) { if (millisElapsedSince(startTime) > LONG_DELAY_MS) fail("timed out"); Thread.yield(); } - } finally { - joinPool(p); } } @@ -205,8 +216,9 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p.getCorePoolSize()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getCorePoolSize()); + } } /** @@ -217,23 +229,25 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(1, p.getKeepAliveTime(SECONDS)); - joinPool(p); + 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(); + ThreadFactory threadFactory = new SimpleThreadFactory(); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10), - tf, + threadFactory, new NoOpREHandler()); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(threadFactory, p.getThreadFactory()); + } } /** @@ -244,10 +258,11 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - ThreadFactory tf = new SimpleThreadFactory(); - p.setThreadFactory(tf); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + ThreadFactory threadFactory = new SimpleThreadFactory(); + p.setThreadFactory(threadFactory); + assertSame(threadFactory, p.getThreadFactory()); + } } /** @@ -258,12 +273,24 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setThreadFactory(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setThreadFactory(null); + shouldThrow(); + } catch (NullPointerException success) {} + } + } + + /** + * The default rejected execution handler is AbortPolicy. + */ + public void testDefaultRejectedExecutionHandler() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p)) { + assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy); } } @@ -271,14 +298,15 @@ public class ThreadPoolExecutorTest exte * getRejectedExecutionHandler returns handler in constructor if not set */ public void testGetRejectedExecutionHandler() { - final RejectedExecutionHandler h = new NoOpREHandler(); + final RejectedExecutionHandler handler = new NoOpREHandler(); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10), - h); - assertSame(h, p.getRejectedExecutionHandler()); - joinPool(p); + handler); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(handler, p.getRejectedExecutionHandler()); + } } /** @@ -290,10 +318,11 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - RejectedExecutionHandler h = new NoOpREHandler(); - p.setRejectedExecutionHandler(h); - assertSame(h, p.getRejectedExecutionHandler()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + RejectedExecutionHandler handler = new NoOpREHandler(); + p.setRejectedExecutionHandler(handler); + assertSame(handler, p.getRejectedExecutionHandler()); + } } /** @@ -304,12 +333,11 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setRejectedExecutionHandler(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setRejectedExecutionHandler(null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -319,28 +347,25 @@ public class ThreadPoolExecutorTest exte */ public void testGetLargestPoolSize() throws InterruptedException { final int THREADS = 3; + final CountDownLatch done = new CountDownLatch(1); final ThreadPoolExecutor p = new ThreadPoolExecutor(THREADS, THREADS, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadsStarted = new CountDownLatch(THREADS); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p, 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(); - done.await(); + await(done); assertEquals(THREADS, p.getLargestPoolSize()); }}); - assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS)); - assertEquals(THREADS, p.getLargestPoolSize()); - } finally { - done.countDown(); - joinPool(p); + await(threadsStarted); assertEquals(THREADS, p.getLargestPoolSize()); } + assertEquals(THREADS, p.getLargestPoolSize()); } /** @@ -352,8 +377,13 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertEquals(3, p.getMaximumPoolSize()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(3, p.getMaximumPoolSize()); + p.setMaximumPoolSize(5); + assertEquals(5, p.getMaximumPoolSize()); + p.setMaximumPoolSize(4); + assertEquals(4, p.getMaximumPoolSize()); + } } /** @@ -361,25 +391,22 @@ public class ThreadPoolExecutorTest exte * become active */ 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)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + 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()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getPoolSize()); - } finally { - done.countDown(); - joinPool(p); } } @@ -387,26 +414,38 @@ public class ThreadPoolExecutorTest exte * getTaskCount increases, but doesn't overestimate, when tasks submitted */ public void testGetTaskCount() throws InterruptedException { + final int TASKS = 3; + final CountDownLatch done = new CountDownLatch(1); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p, 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(); - assertEquals(1, p.getTaskCount()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getTaskCount()); - } finally { - done.countDown(); - joinPool(p); + 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()); } /** @@ -417,10 +456,11 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p.isShutdown()); - try { p.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p.isShutdown()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.isShutdown()); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.isShutdown()); + } } /** @@ -431,26 +471,28 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - 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()); - p.shutdown(); - assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); + 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(randomExpiredTimeout(), + randomTimeUnit())); + 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()); + } } /** @@ -461,24 +503,24 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - assertFalse(p.isTerminated()); - try { + 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.isTerminated()); + assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); 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()); } - assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); } /** @@ -489,59 +531,57 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); assertFalse(p.isTerminating()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); 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()); } - 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 { - final BlockingQueue q = new ArrayBlockingQueue(10); + final CountDownLatch done = new CountDownLatch(1); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(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]; + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + FutureTask[] rtasks = new FutureTask[5]; + @SuppressWarnings("unchecked") + FutureTask[] tasks = (FutureTask[])rtasks; for (int i = 0; i < tasks.length; i++) { - Callable task = new CheckedCallable() { + Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); assertSame(q, p.getQueue()); - done.await(); + await(done); return Boolean.TRUE; }}; - tasks[i] = new FutureTask(task); + tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertSame(q, p.getQueue()); assertFalse(q.contains(tasks[0])); assertTrue(q.contains(tasks[tasks.length - 1])); assertEquals(tasks.length - 1, q.size()); - } finally { - done.countDown(); - joinPool(p); } } @@ -549,24 +589,24 @@ public class ThreadPoolExecutorTest exte * remove(task) removes queued task, and fails to remove active task */ public void testRemove() throws InterruptedException { - BlockingQueue q = new ArrayBlockingQueue(10); + final CountDownLatch done = new CountDownLatch(1); + BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, q); - Runnable[] tasks = new Runnable[5]; - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p, done)) { + Runnable[] tasks = new Runnable[6]; + final CountDownLatch threadStarted = new CountDownLatch(1); for (int i = 0; i < tasks.length; i++) { tasks[i] = new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); }}; p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.remove(tasks[0])); assertTrue(q.contains(tasks[4])); assertTrue(q.contains(tasks[3])); @@ -576,9 +616,6 @@ public class ThreadPoolExecutorTest exte assertTrue(q.contains(tasks[3])); assertTrue(p.remove(tasks[3])); assertFalse(q.contains(tasks[3])); - } finally { - done.countDown(); - joinPool(p); } } @@ -588,24 +625,26 @@ public class ThreadPoolExecutorTest exte public void testPurge() throws InterruptedException { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - final BlockingQueue q = new ArrayBlockingQueue(10); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, q); - FutureTask[] tasks = new FutureTask[5]; - try { + try (PoolCleaner cleaner = cleaner(p, done)) { + FutureTask[] rtasks = new FutureTask[5]; + @SuppressWarnings("unchecked") + FutureTask[] tasks = (FutureTask[])rtasks; for (int i = 0; i < tasks.length; i++) { - Callable task = new CheckedCallable() { + Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); return Boolean.TRUE; }}; - tasks[i] = new FutureTask(task); + tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(tasks.length, p.getTaskCount()); assertEquals(tasks.length - 1, q.size()); assertEquals(1L, p.getActiveCount()); @@ -618,9 +657,6 @@ public class ThreadPoolExecutorTest exte p.purge(); // Nothing to do assertEquals(tasks.length - 3, q.size()); assertEquals(tasks.length - 2, p.getTaskCount()); - } finally { - done.countDown(); - joinPool(p); } } @@ -636,17 +672,17 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(poolSize, poolSize, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - CountDownLatch threadsStarted = new CountDownLatch(poolSize); - CheckedRunnable waiter = new CheckedRunnable() { public void realRun() { + final CountDownLatch threadsStarted = new CountDownLatch(poolSize); + Runnable waiter = new CheckedRunnable() { public void realRun() { threadsStarted.countDown(); try { - MILLISECONDS.sleep(2 * LONG_DELAY_MS); + MILLISECONDS.sleep(LONGER_DELAY_MS); } catch (InterruptedException success) {} ran.getAndIncrement(); }}; for (int i = 0; i < count; i++) p.execute(waiter); - assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadsStarted); assertEquals(poolSize, p.getActiveCount()); assertEquals(0, p.getCompletedTaskCount()); final List queuedTasks; @@ -727,7 +763,7 @@ public class ThreadPoolExecutorTest exte public void testConstructorNullPointerException() { try { new ThreadPoolExecutor(1, 2, 1L, SECONDS, - (BlockingQueue) null); + (BlockingQueue) null); shouldThrow(); } catch (NullPointerException success) {} } @@ -798,7 +834,7 @@ public class ThreadPoolExecutorTest exte public void testConstructorNullPointerException2() { try { new ThreadPoolExecutor(1, 2, 1L, SECONDS, - (BlockingQueue) null, + (BlockingQueue) null, new SimpleThreadFactory()); shouldThrow(); } catch (NullPointerException success) {} @@ -882,7 +918,7 @@ public class ThreadPoolExecutorTest exte public void testConstructorNullPointerException4() { try { new ThreadPoolExecutor(1, 2, 1L, SECONDS, - (BlockingQueue) null, + (BlockingQueue) null, new NoOpREHandler()); shouldThrow(); } catch (NullPointerException success) {} @@ -971,7 +1007,7 @@ public class ThreadPoolExecutorTest exte public void testConstructorNullPointerException6() { try { new ThreadPoolExecutor(1, 2, 1L, SECONDS, - (BlockingQueue) null, + (BlockingQueue) null, new SimpleThreadFactory(), new NoOpREHandler()); shouldThrow(); @@ -1008,308 +1044,165 @@ public class ThreadPoolExecutorTest exte * 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)); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - try { + 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() { + Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); return Boolean.TRUE; }}; p.submit(task).get(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); // ensure quiescence t.interrupt(); - awaitTermination(t, MEDIUM_DELAY_MS); - } finally { - done.countDown(); - joinPool(p); + awaitTermination(t); } } /** - * execute throws RejectedExecutionException if saturated. + * Submitted tasks are rejected when saturated or shutdown */ - public void testSaturatedExecute() { - ThreadPoolExecutor p = - new ThreadPoolExecutor(1, 1, - LONG_DELAY_MS, MILLISECONDS, - new ArrayBlockingQueue(1)); + public void testSubmittedTasksRejectedWhenSaturatedOrShutdown() throws InterruptedException { + final ThreadPoolExecutor p = new ThreadPoolExecutor( + 1, 1, 1, SECONDS, new ArrayBlockingQueue(1)); + final int saturatedSize = saturatedSize(p); + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); + final CountDownLatch threadsStarted = new CountDownLatch(p.getMaximumPoolSize()); 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) { + final Runnable r = () -> { + threadsStarted.countDown(); + for (;;) { try { - p.execute(task); - shouldThrow(); - } catch (RejectedExecutionException success) {} - assertTrue(p.getTaskCount() <= 2); - } - } finally { - done.countDown(); - joinPool(p); - } - } - - /** - * submit(runnable) throws RejectedExecutionException if saturated. - */ - public void testSaturatedSubmitRunnable() { - ThreadPoolExecutor p = - new ThreadPoolExecutor(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.submit(task); - for (int i = 0; i < 2; ++i) { + return; + } catch (InterruptedException shutdownNowDeliberatelyIgnored) {} + }}; + final Callable c = () -> { + threadsStarted.countDown(); + for (;;) { try { - p.execute(task); - shouldThrow(); - } catch (RejectedExecutionException success) {} - assertTrue(p.getTaskCount() <= 2); - } - } finally { - done.countDown(); - joinPool(p); - } - } - - /** - * submit(callable) throws RejectedExecutionException if saturated. - */ - public void testSaturatedSubmitCallable() { - ThreadPoolExecutor p = - new ThreadPoolExecutor(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.submit(Executors.callable(task)); - for (int i = 0; i < 2; ++i) { - try { - p.execute(task); - shouldThrow(); - } catch (RejectedExecutionException success) {} - assertTrue(p.getTaskCount() <= 2); + return Boolean.TRUE; + } catch (InterruptedException shutdownNowDeliberatelyIgnored) {} + }}; + final boolean shutdownNow = rnd.nextBoolean(); + + try (PoolCleaner cleaner = cleaner(p, done)) { + // saturate + for (int i = saturatedSize; i--> 0; ) { + switch (rnd.nextInt(4)) { + case 0: p.execute(r); break; + case 1: assertFalse(p.submit(r).isDone()); break; + case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break; + case 3: assertFalse(p.submit(c).isDone()); break; + } } - } finally { - done.countDown(); - joinPool(p); - } - } - /** - * executor using CallerRunsPolicy runs task if saturated. - */ - public void testSaturatedExecute2() { - RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy(); - final 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 < tasks.length; ++i) - tasks[i] = new TrackedNoOpRunnable(); - TrackedLongRunnable mr = new TrackedLongRunnable(); - p.execute(mr); - for (int i = 0; i < tasks.length; ++i) - p.execute(tasks[i]); - for (int i = 1; i < tasks.length; ++i) - assertTrue(tasks[i].done); - try { p.shutdownNow(); } catch (SecurityException ok) { return; } - } finally { - joinPool(p); - } - } + await(threadsStarted); + assertTaskSubmissionsAreRejected(p); - /** - * executor using DiscardPolicy drops task if saturated. - */ - public void testSaturatedExecute3() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy(); - final 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 < tasks.length; ++i) - tasks[i] = new TrackedNoOpRunnable(); - p.execute(new TrackedLongRunnable()); - for (TrackedNoOpRunnable task : tasks) - p.execute(task); - for (TrackedNoOpRunnable task : tasks) - assertFalse(task.done); - try { p.shutdownNow(); } catch (SecurityException ok) { return; } - } finally { - joinPool(p); - } + if (shutdownNow) + p.shutdownNow(); + else + p.shutdown(); + // Pool is shutdown, but not yet terminated + assertTaskSubmissionsAreRejected(p); + assertFalse(p.isTerminated()); + + done.countDown(); // release blocking tasks + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + + assertTaskSubmissionsAreRejected(p); + } + assertEquals(saturatedSize(p) + - (shutdownNow ? p.getQueue().remainingCapacity() : 0), + p.getCompletedTaskCount()); } /** * executor using DiscardOldestPolicy drops oldest task if saturated. */ - public void testSaturatedExecute4() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy(); + public void testSaturatedExecute_DiscardOldestPolicy() { + 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), - h); - try { - p.execute(new TrackedLongRunnable()); - TrackedLongRunnable r2 = new TrackedLongRunnable(); + new DiscardOldestPolicy()); + try (PoolCleaner cleaner = cleaner(p, done)) { + 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); - } - } - - /** - * execute throws RejectedExecutionException if shutdown - */ - public void testRejectedExecutionExceptionOnShutdown() { - ThreadPoolExecutor p = - new ThreadPoolExecutor(1, 1, - LONG_DELAY_MS, MILLISECONDS, - new ArrayBlockingQueue(1)); - try { p.shutdown(); } catch (SecurityException ok) { return; } - try { - p.execute(new NoOpRunnable()); - shouldThrow(); - } catch (RejectedExecutionException success) {} - - joinPool(p); - } - - /** - * execute using CallerRunsPolicy drops task on shutdown - */ - public void testCallerRunsOnShutdown() { - RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy(); - final ThreadPoolExecutor p = - new ThreadPoolExecutor(1, 1, - LONG_DELAY_MS, MILLISECONDS, - new ArrayBlockingQueue(1), h); - - try { p.shutdown(); } catch (SecurityException ok) { return; } - try { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - p.execute(r); - assertFalse(r.done); - } finally { - joinPool(p); - } - } - - /** - * 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); - - try { p.shutdown(); } catch (SecurityException ok) { return; } - try { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - p.execute(r); - assertFalse(r.done); - } finally { - joinPool(p); } + assertEquals(LatchAwaiter.DONE, r1.state); + assertEquals(LatchAwaiter.NEW, r2.state); + assertEquals(LatchAwaiter.DONE, r3.state); } /** * execute using DiscardOldestPolicy drops task on shutdown */ public void testDiscardOldestOnShutdown() { - RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy(); - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), - h); + new 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 + * Submitting null tasks throws NullPointerException */ - public void testExecuteNull() { - ThreadPoolExecutor p = - new ThreadPoolExecutor(1, 2, 1L, SECONDS, + public void testNullTaskSubmission() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 2, + 1L, SECONDS, new ArrayBlockingQueue(10)); - try { - p.execute(null); - shouldThrow(); - } catch (NullPointerException success) {} - - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertNullTaskSubmissionThrowsNullPointerException(p); + } } /** * setCorePoolSize of negative value throws IllegalArgumentException */ public void testCorePoolSizeIllegalArgumentException() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setCorePoolSize(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { p.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setCorePoolSize(-1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(p); } /** @@ -1317,18 +1210,16 @@ public class ThreadPoolExecutorTest exte * given a value less the core pool size */ public void testMaximumPoolSizeIllegalArgumentException() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setMaximumPoolSize(1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { p.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setMaximumPoolSize(1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(p); } /** @@ -1336,18 +1227,16 @@ public class ThreadPoolExecutorTest exte * if given a negative value */ public void testMaximumPoolSizeIllegalArgumentException2() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setMaximumPoolSize(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { p.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setMaximumPoolSize(-1); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(p); } /** @@ -1355,27 +1244,28 @@ public class ThreadPoolExecutorTest exte * max pool size result in IllegalArgumentException. */ public void testPoolSizeInvariants() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - 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()); + 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()); + } } - joinPool(p); } /** @@ -1383,18 +1273,16 @@ public class ThreadPoolExecutorTest exte * when given a negative value */ public void testKeepAliveTimeIllegalArgumentException() { - ThreadPoolExecutor p = + final ThreadPoolExecutor p = new ThreadPoolExecutor(2, 3, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - p.setKeepAliveTime(-1,MILLISECONDS); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - try { p.shutdown(); } catch (SecurityException ok) { return; } + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setKeepAliveTime(-1, MILLISECONDS); + shouldThrow(); + } catch (IllegalArgumentException success) {} } - joinPool(p); } /** @@ -1402,9 +1290,11 @@ public class ThreadPoolExecutorTest exte */ public void testTerminated() { ExtendedTPE p = new ExtendedTPE(); - try { p.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p.terminatedCalled()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.terminatedCalled()); + assertTrue(p.isShutdown()); + } } /** @@ -1412,7 +1302,7 @@ public class ThreadPoolExecutorTest exte */ public void testBeforeAfter() throws InterruptedException { ExtendedTPE p = new ExtendedTPE(); - try { + try (PoolCleaner cleaner = cleaner(p)) { final CountDownLatch done = new CountDownLatch(1); p.execute(new CheckedRunnable() { public void realRun() { @@ -1422,9 +1312,6 @@ public class ThreadPoolExecutorTest exte assertEquals(0, done.getCount()); assertTrue(p.afterCalled()); assertTrue(p.beforeCalled()); - try { p.shutdown(); } catch (SecurityException ok) { return; } - } finally { - joinPool(p); } } @@ -1432,16 +1319,14 @@ public class ThreadPoolExecutorTest exte * completed submit of callable returns result */ public void testSubmitCallable() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new StringTask()); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -1449,16 +1334,14 @@ public class ThreadPoolExecutorTest exte * completed submit of runnable returns successfully */ public void testSubmitRunnable() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable()); future.get(); assertTrue(future.isDone()); - } finally { - joinPool(e); } } @@ -1466,16 +1349,14 @@ public class ThreadPoolExecutorTest exte * completed submit of (runnable, result) returns result */ public void testSubmitRunnable2() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable(), TEST_STRING); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -1483,33 +1364,31 @@ public class ThreadPoolExecutorTest exte * invokeAny(null) throws NPE */ public void testInvokeAny1() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAny(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * invokeAny(empty collection) throws IAE + * invokeAny(empty collection) throws IllegalArgumentException */ public void testInvokeAny2() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } @@ -1522,16 +1401,15 @@ public class ThreadPoolExecutorTest exte 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 { + 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); } } @@ -1539,19 +1417,19 @@ public class ThreadPoolExecutorTest exte * invokeAny(c) throws ExecutionException if no task completes */ public void testInvokeAny4() throws Exception { - ExecutorService e = + final 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); + 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); + } } } @@ -1559,18 +1437,16 @@ public class ThreadPoolExecutorTest exte * invokeAny(c) returns result of some task */ public void testInvokeAny5() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> l = new ArrayList>(); + 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); } } @@ -1578,32 +1454,31 @@ public class ThreadPoolExecutorTest exte * invokeAll(null) throws NPE */ public void testInvokeAll1() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - e.invokeAll(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * invokeAll(empty collection) returns empty collection + * invokeAll(empty collection) returns empty list */ public void testInvokeAll2() throws InterruptedException { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> r = e.invokeAll(new ArrayList>()); + final Collection> emptyCollection + = Collections.emptyList(); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(emptyCollection); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -1611,19 +1486,18 @@ public class ThreadPoolExecutorTest exte * invokeAll(c) throws NPE if c has null elements */ public void testInvokeAll3() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new StringTask()); + l.add(null); + try { + e.invokeAll(l); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1631,12 +1505,12 @@ public class ThreadPoolExecutorTest exte * get of element of invokeAll(c) throws exception on failed task */ public void testInvokeAll4() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> l = new ArrayList>(); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1646,8 +1520,6 @@ public class ThreadPoolExecutorTest exte } catch (ExecutionException success) { assertTrue(success.getCause() instanceof NullPointerException); } - } finally { - joinPool(e); } } @@ -1655,20 +1527,18 @@ public class ThreadPoolExecutorTest exte * invokeAll(c) returns results of all completed tasks */ public void testInvokeAll5() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> l = new ArrayList>(); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); assertEquals(2, futures.size()); for (Future future : futures) assertSame(TEST_STRING, future.get()); - } finally { - joinPool(e); } } @@ -1676,16 +1546,15 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(null) throws NPE */ public void testTimedInvokeAny1() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1693,40 +1562,39 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(,,null) throws NPE */ public void testTimedInvokeAnyNullTimeUnit() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new StringTask()); + try { + e.invokeAny(l, randomTimeout(), null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * timed invokeAny(empty collection) throws IAE + * timed invokeAny(empty collection) throws IllegalArgumentException */ public void testTimedInvokeAny2() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>(), + randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } /** - * timed invokeAny(c) throws NPE if c has null elements + * timed invokeAny(c) throws NullPointerException if c has null elements */ public void testTimedInvokeAny3() throws Exception { final CountDownLatch latch = new CountDownLatch(1); @@ -1734,16 +1602,15 @@ public class ThreadPoolExecutorTest exte 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 { + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); + try { + e.invokeAny(l, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} latch.countDown(); - joinPool(e); } } @@ -1751,19 +1618,21 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(c) throws ExecutionException if no task completes */ public void testTimedInvokeAny4() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + long startTime = System.nanoTime(); + List> l = new ArrayList<>(); + l.add(new NPETask()); + try { + e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); } } @@ -1771,18 +1640,18 @@ public class ThreadPoolExecutorTest exte * timed invokeAny(c) returns result of some task */ public void testTimedInvokeAny5() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> l = new ArrayList>(); + try (PoolCleaner cleaner = cleaner(e)) { + long startTime = System.nanoTime(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); - String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); assertSame(TEST_STRING, result); - } finally { - joinPool(e); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); } } @@ -1790,16 +1659,15 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(null) throws NPE */ public void testTimedInvokeAll1() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1807,34 +1675,34 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(,,null) throws NPE */ public void testTimedInvokeAllNullTimeUnit() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new StringTask()); + try { + e.invokeAll(l, randomTimeout(), null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * timed invokeAll(empty collection) returns empty collection + * timed invokeAll(empty collection) returns empty list */ public void testTimedInvokeAll2() throws InterruptedException { - ExecutorService e = + final 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 Collection> emptyCollection + = Collections.emptyList(); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = + e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit()); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -1842,19 +1710,18 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) throws NPE if c has null elements */ public void testTimedInvokeAll3() throws Exception { - ExecutorService e = + final 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); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new StringTask()); + l.add(null); + try { + e.invokeAll(l, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1862,22 +1729,22 @@ public class ThreadPoolExecutorTest exte * get of element of invokeAll(c) throws exception on failed task */ public void testTimedInvokeAll4() throws Exception { - ExecutorService e = + final 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); + 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); + } } } @@ -1885,21 +1752,19 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) returns results of all completed tasks */ public void testTimedInvokeAll5() throws Exception { - ExecutorService e = + final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); - try { - List> l = new ArrayList>(); + 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); } } @@ -1907,22 +1772,28 @@ 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 { - for (long timeout = timeoutMillis();;) { + for (long timeout = timeoutMillis();;) { + final CountDownLatch done = new CountDownLatch(1); + final Callable waiter = new CheckedCallable() { + public String realCall() { + try { done.await(LONG_DELAY_MS, MILLISECONDS); } + catch (InterruptedException ok) {} + return "1"; }}; + final ExecutorService p = + new ThreadPoolExecutor(2, 2, + LONG_DELAY_MS, MILLISECONDS, + new ArrayBlockingQueue(10)); + try (PoolCleaner cleaner = cleaner(p, done)) { List> tasks = new ArrayList<>(); tasks.add(new StringTask("0")); - tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING)); + tasks.add(waiter); tasks.add(new StringTask("2")); long startTime = System.nanoTime(); List> futures = - e.invokeAll(tasks, timeout, MILLISECONDS); + p.invokeAll(tasks, timeout, MILLISECONDS); assertEquals(tasks.size(), futures.size()); assertTrue(millisElapsedSince(startTime) >= timeout); - for (Future future : futures) + for (Future future : futures) assertTrue(future.isDone()); assertTrue(futures.get(1).isCancelled()); try { @@ -1935,8 +1806,6 @@ public class ThreadPoolExecutorTest exte fail("expected exactly one task to be cancelled"); } } - } finally { - joinPool(e); } } @@ -1950,7 +1819,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new LinkedBlockingQueue(), new FailingThreadFactory()); - try { + try (PoolCleaner cleaner = cleaner(e)) { final int TASKS = 100; final CountDownLatch done = new CountDownLatch(TASKS); for (int k = 0; k < TASKS; ++k) @@ -1958,9 +1827,7 @@ public class ThreadPoolExecutorTest exte public void realRun() { done.countDown(); }}); - assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); - } finally { - joinPool(e); + await(done); } } @@ -1972,8 +1839,9 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue(10)); - assertFalse(p.allowsCoreThreadTimeOut()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.allowsCoreThreadTimeOut()); + } } /** @@ -1985,8 +1853,8 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 10, keepAliveTime, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); p.allowCoreThreadTimeOut(true); p.execute(new CheckedRunnable() { public void realRun() { @@ -2001,8 +1869,6 @@ public class ThreadPoolExecutorTest exte Thread.yield(); assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); assertEquals(0, p.getPoolSize()); - } finally { - joinPool(p); } } @@ -2015,8 +1881,8 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(2, 10, keepAliveTime, MILLISECONDS, new ArrayBlockingQueue(10)); - final CountDownLatch threadStarted = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); p.allowCoreThreadTimeOut(false); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -2025,8 +1891,6 @@ public class ThreadPoolExecutorTest exte }}); delay(2 * keepAliveTime); assertTrue(p.getPoolSize() >= 1); - } finally { - joinPool(p); } } @@ -2044,8 +1908,8 @@ public class ThreadPoolExecutorTest exte final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 30, 60, SECONDS, - new ArrayBlockingQueue(30)); - try { + new ArrayBlockingQueue(30)); + try (PoolCleaner cleaner = cleaner(p)) { for (int i = 0; i < nTasks; ++i) { for (;;) { try { @@ -2056,9 +1920,116 @@ public class ThreadPoolExecutorTest exte } } // enough time to run all tasks - assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS)); - } finally { - joinPool(p); + await(done, nTasks * SHORT_DELAY_MS); + } + } + + /** + * get(cancelled task) throws CancellationException + */ + public void testGet_cancelled() throws Exception { + final CountDownLatch done = new CountDownLatch(1); + final ExecutorService e = + new ThreadPoolExecutor(1, 1, + LONG_DELAY_MS, MILLISECONDS, + new LinkedBlockingQueue()); + try (PoolCleaner cleaner = cleaner(e, done)) { + final CountDownLatch blockerStarted = 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()); + } + } + } + + /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */ + public void testStandardRejectedExecutionHandlers() { + final ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, 1, SECONDS, + new ArrayBlockingQueue(1)); + final AtomicReference thread = new AtomicReference<>(); + final Runnable r = new Runnable() { public void run() { + thread.set(Thread.currentThread()); }}; + + try { + new AbortPolicy().rejectedExecution(r, p); + shouldThrow(); + } catch (RejectedExecutionException success) {} + assertNull(thread.get()); + + new DiscardPolicy().rejectedExecution(r, p); + assertNull(thread.get()); + + new CallerRunsPolicy().rejectedExecution(r, p); + assertSame(Thread.currentThread(), thread.get()); + + // check that pool was not perturbed by handlers + assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy); + assertEquals(0, p.getTaskCount()); + assertTrue(p.getQueue().isEmpty()); + } + + public void testThreadFactoryReturnsTerminatedThread_shouldThrow() { + if (!testImplementationDetails) + return; + + ThreadFactory returnsTerminatedThread = runnableIgnored -> { + Thread thread = new Thread(() -> {}); + thread.start(); + try { thread.join(); } + catch (InterruptedException ex) { throw new Error(ex); } + return thread; + }; + ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, 1, SECONDS, + new ArrayBlockingQueue(1), + returnsTerminatedThread); + try (PoolCleaner cleaner = cleaner(p)) { + assertThrows(IllegalThreadStateException.class, + () -> p.execute(() -> {})); + } + } + + public void testThreadFactoryReturnsStartedThread_shouldThrow() { + if (!testImplementationDetails) + return; + + CountDownLatch latch = new CountDownLatch(1); + Runnable awaitLatch = () -> { + try { latch.await(); } + catch (InterruptedException ex) { throw new Error(ex); }}; + ThreadFactory returnsStartedThread = runnable -> { + Thread thread = new Thread(awaitLatch); + thread.start(); + return thread; + }; + ThreadPoolExecutor p = + new ThreadPoolExecutor(1, 1, 1, SECONDS, + new ArrayBlockingQueue(1), + returnsStartedThread); + try (PoolCleaner cleaner = cleaner(p)) { + assertThrows(IllegalThreadStateException.class, + () -> p.execute(() -> {})); + latch.countDown(); } }