--- jsr166/src/test/tck/ThreadPoolExecutorTest.java 2015/10/05 22:09:02 1.102 +++ jsr166/src/test/tck/ThreadPoolExecutorTest.java 2019/09/06 18:43:35 1.126 @@ -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; @@ -92,7 +98,7 @@ public class ThreadPoolExecutorTest exte final Runnable task = new CheckedRunnable() { public void realRun() { done.countDown(); }}; p.execute(task); - assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); + await(done); } } @@ -101,23 +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)); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { 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()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getActiveCount()); - done.countDown(); } } @@ -187,13 +192,13 @@ public class ThreadPoolExecutorTest exte 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) @@ -277,6 +282,19 @@ public class ThreadPoolExecutorTest exte } /** + * 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); + } + } + + /** * getRejectedExecutionHandler returns handler in constructor if not set */ public void testGetRejectedExecutionHandler() { @@ -329,24 +347,23 @@ 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)); - try (PoolCleaner cleaner = cleaner(p)) { - final CountDownLatch threadsStarted = new CountDownLatch(THREADS); - final CountDownLatch done = new CountDownLatch(1); + 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(LONG_DELAY_MS, MILLISECONDS)); + await(threadsStarted); assertEquals(THREADS, p.getLargestPoolSize()); - done.countDown(); // release pool } assertEquals(THREADS, p.getLargestPoolSize()); } @@ -374,23 +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)); - try (PoolCleaner cleaner = cleaner(p)) { - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); + 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(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getPoolSize()); - done.countDown(); // release pool } } @@ -411,9 +427,9 @@ public class ThreadPoolExecutorTest exte p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getTaskCount()); assertEquals(0, p.getCompletedTaskCount()); for (int i = 0; i < TASKS; i++) { @@ -422,7 +438,7 @@ public class ThreadPoolExecutorTest exte public void realRun() throws InterruptedException { threadStarted.countDown(); assertEquals(1 + TASKS, p.getTaskCount()); - done.await(); + await(done); }}); } assertEquals(1 + TASKS, p.getTaskCount()); @@ -461,8 +477,8 @@ public class ThreadPoolExecutorTest exte 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)); + assertFalse(p.awaitTermination(randomExpiredTimeout(), + randomTimeUnit())); long timeoutNanos = 999999L; long startTime = System.nanoTime(); assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS)); @@ -495,9 +511,9 @@ public class ThreadPoolExecutorTest exte public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } @@ -523,9 +539,9 @@ public class ThreadPoolExecutorTest exte public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } @@ -539,32 +555,31 @@ public class ThreadPoolExecutorTest exte * 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); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { 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()); - done.await(); + await(done); return Boolean.TRUE; }}; tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(LONG_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()); - done.countDown(); } } @@ -572,24 +587,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); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { 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(); - done.await(); + await(done); }}; p.execute(tasks[i]); } - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.remove(tasks[0])); assertTrue(q.contains(tasks[4])); assertTrue(q.contains(tasks[3])); @@ -599,7 +614,6 @@ public class ThreadPoolExecutorTest exte assertTrue(q.contains(tasks[3])); assertTrue(p.remove(tasks[3])); assertFalse(q.contains(tasks[3])); - done.countDown(); } } @@ -609,7 +623,7 @@ 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, @@ -620,13 +634,13 @@ public class ThreadPoolExecutorTest exte Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); return Boolean.TRUE; }}; tasks[i] = new FutureTask(task); p.execute(tasks[i]); } - assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(tasks.length, p.getTaskCount()); assertEquals(tasks.length - 1, q.size()); assertEquals(1L, p.getActiveCount()); @@ -658,13 +672,13 @@ public class ThreadPoolExecutorTest exte 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; @@ -1026,173 +1040,95 @@ 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)); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); Thread t = newStartedThread(new CheckedInterruptedRunnable() { public void realRun() throws Exception { 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(LONG_DELAY_MS, MILLISECONDS)); + await(threadStarted); // ensure quiescence t.interrupt(); - awaitTermination(t, MEDIUM_DELAY_MS); - done.countDown(); + awaitTermination(t); } } /** - * execute throws RejectedExecutionException if saturated. + * Submitted tasks are rejected when saturated or shutdown */ - public void testSaturatedExecute() { - 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 { - done.await(); - }}; - for (int i = 0; i < 2; ++i) - p.execute(task); - for (int i = 0; i < 2; ++i) { + 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); + final Runnable r = () -> { + threadsStarted.countDown(); + for (;;) { 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 { 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); - } - 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 { 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; + } } - done.countDown(); - } - } - /** - * executor using CallerRunsPolicy runs task if saturated. - */ - public void testSaturatedExecute2() { - 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 { - done.await(); - }}; - p.execute(blocker); - TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5]; - for (int i = 0; i < tasks.length; i++) - tasks[i] = new TrackedNoOpRunnable(); - for (int i = 0; i < tasks.length; i++) - p.execute(tasks[i]); - for (int i = 1; i < tasks.length; i++) - assertTrue(tasks[i].done); - assertFalse(tasks[0].done); // waiting in queue - done.countDown(); - } - } + await(threadsStarted); + assertTaskSubmissionsAreRejected(p); - /** - * executor using DiscardPolicy drops task if saturated. - */ - public void testSaturatedExecute3() { - 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)); + if (shutdownNow) + p.shutdownNow(); + else + p.shutdown(); + // Pool is shutdown, but not yet terminated + assertTaskSubmissionsAreRejected(p); + assertFalse(p.isTerminated()); - for (TrackedNoOpRunnable task : tasks) - p.execute(task); - for (int i = 1; i < tasks.length; i++) - assertFalse(tasks[i].done); - done.countDown(); + done.countDown(); // release blocking tasks + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + + assertTaskSubmissionsAreRejected(p); } - for (int i = 1; i < tasks.length; i++) - assertFalse(tasks[i].done); - assertTrue(tasks[0].done); // was waiting in queue + assertEquals(saturatedSize(p) + - (shutdownNow ? p.getQueue().remainingCapacity() : 0), + p.getCompletedTaskCount()); } /** * executor using DiscardOldestPolicy drops oldest task if saturated. */ - public void testSaturatedExecute4() { + public void testSaturatedExecute_DiscardOldestPolicy() { final CountDownLatch done = new CountDownLatch(1); LatchAwaiter r1 = awaiter(done); LatchAwaiter r2 = awaiter(done); @@ -1201,8 +1137,8 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), - new ThreadPoolExecutor.DiscardOldestPolicy()); - try (PoolCleaner cleaner = cleaner(p)) { + new DiscardOldestPolicy()); + try (PoolCleaner cleaner = cleaner(p, done)) { assertEquals(LatchAwaiter.NEW, r1.state); assertEquals(LatchAwaiter.NEW, r2.state); assertEquals(LatchAwaiter.NEW, r3.state); @@ -1212,7 +1148,6 @@ public class ThreadPoolExecutorTest exte p.execute(r3); assertFalse(p.getQueue().contains(r2)); assertTrue(p.getQueue().contains(r3)); - done.countDown(); } assertEquals(LatchAwaiter.DONE, r1.state); assertEquals(LatchAwaiter.NEW, r2.state); @@ -1220,59 +1155,6 @@ public class ThreadPoolExecutorTest exte } /** - * execute throws RejectedExecutionException if shutdown - */ - public void testRejectedExecutionExceptionOnShutdown() { - 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) {} - } - } - - /** - * 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 (PoolCleaner cleaner = cleaner(p)) { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - p.execute(r); - assertFalse(r.done); - } - } - - /** - * execute using DiscardPolicy drops task on shutdown - */ - public void testDiscardOnShutdown() { - 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 (PoolCleaner cleaner = cleaner(p)) { - TrackedNoOpRunnable r = new TrackedNoOpRunnable(); - p.execute(r); - assertFalse(r.done); - } - } - - /** * execute using DiscardOldestPolicy drops task on shutdown */ public void testDiscardOldestOnShutdown() { @@ -1280,7 +1162,7 @@ public class ThreadPoolExecutorTest exte new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(1), - new ThreadPoolExecutor.DiscardOldestPolicy()); + new DiscardOldestPolicy()); try { p.shutdown(); } catch (SecurityException ok) { return; } try (PoolCleaner cleaner = cleaner(p)) { @@ -1291,18 +1173,15 @@ public class ThreadPoolExecutorTest exte } /** - * execute(null) throws NPE + * Submitting null tasks throws NullPointerException */ - public void testExecuteNull() { + public void testNullTaskSubmission() { 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) {} + assertNullTaskSubmissionThrowsNullPointerException(p); } } @@ -1494,7 +1373,7 @@ public class ThreadPoolExecutorTest exte } /** - * invokeAny(empty collection) throws IAE + * invokeAny(empty collection) throws IllegalArgumentException */ public void testInvokeAny2() throws Exception { final ExecutorService e = @@ -1519,7 +1398,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1539,7 +1418,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -1559,7 +1438,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -1584,15 +1463,17 @@ public class ThreadPoolExecutorTest exte } /** - * invokeAll(empty collection) returns empty collection + * invokeAll(empty collection) returns empty list */ public void testInvokeAll2() throws InterruptedException { final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + final Collection> emptyCollection + = Collections.emptyList(); try (PoolCleaner cleaner = cleaner(e)) { - List> r = e.invokeAll(new ArrayList>()); + List> r = e.invokeAll(emptyCollection); assertTrue(r.isEmpty()); } } @@ -1606,7 +1487,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1625,7 +1506,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1647,7 +1528,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -1667,7 +1548,7 @@ public class ThreadPoolExecutorTest exte new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { try { - e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAny(null, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } @@ -1682,17 +1563,17 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { - e.invokeAny(l, MEDIUM_DELAY_MS, null); + 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 { final ExecutorService e = @@ -1702,14 +1583,14 @@ public class ThreadPoolExecutorTest exte try (PoolCleaner cleaner = cleaner(e)) { try { e.invokeAny(new ArrayList>(), - MEDIUM_DELAY_MS, MILLISECONDS); + 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); @@ -1718,11 +1599,11 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAny(l, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} latch.countDown(); @@ -1738,14 +1619,16 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + long startTime = System.nanoTime(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (ExecutionException success) { assertTrue(success.getCause() instanceof NullPointerException); } + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); } } @@ -1758,11 +1641,13 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + 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); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS); } } @@ -1776,7 +1661,7 @@ public class ThreadPoolExecutorTest exte new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { try { - e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAll(null, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } @@ -1791,26 +1676,28 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { - e.invokeAll(l, MEDIUM_DELAY_MS, null); + 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 { final ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); + final Collection> emptyCollection + = Collections.emptyList(); try (PoolCleaner cleaner = cleaner(e)) { - List> r = e.invokeAll(new ArrayList>(), - MEDIUM_DELAY_MS, MILLISECONDS); + List> r = + e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit()); assertTrue(r.isEmpty()); } } @@ -1824,11 +1711,11 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAll(l, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } @@ -1843,10 +1730,10 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); assertEquals(1, futures.size()); try { futures.get(0).get(); @@ -1866,7 +1753,7 @@ public class ThreadPoolExecutorTest exte LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = @@ -1881,19 +1768,25 @@ public class ThreadPoolExecutorTest exte * timed invokeAll(c) cancels tasks not completed by timeout */ public void testTimedInvokeAll6() throws Exception { - final ExecutorService e = - new ThreadPoolExecutor(2, 2, - LONG_DELAY_MS, MILLISECONDS, - new ArrayBlockingQueue(10)); - try (PoolCleaner cleaner = cleaner(e)) { - 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) @@ -1930,7 +1823,7 @@ public class ThreadPoolExecutorTest exte public void realRun() { done.countDown(); }}); - assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); + await(done); } } @@ -2023,7 +1916,7 @@ public class ThreadPoolExecutorTest exte } } // enough time to run all tasks - assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS)); + await(done, nTasks * SHORT_DELAY_MS); } } @@ -2031,13 +1924,13 @@ public class ThreadPoolExecutorTest exte * 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)) { + try (PoolCleaner cleaner = cleaner(e, done)) { 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() @@ -2047,7 +1940,7 @@ public class ThreadPoolExecutorTest exte }}; futures.add(e.submit(r)); } - assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS)); + await(blockerStarted); for (Future future : futures) future.cancel(false); for (Future future : futures) { try { @@ -2061,7 +1954,78 @@ public class ThreadPoolExecutorTest exte assertTrue(future.isCancelled()); assertTrue(future.isDone()); } - done.countDown(); + } + } + + /** 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(); } }