--- jsr166/src/test/tck/ScheduledExecutorTest.java 2015/10/05 21:54:33 1.66 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2017/05/29 22:44:27 1.94 @@ -7,9 +7,12 @@ */ import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -17,15 +20,18 @@ 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.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; import junit.framework.Test; import junit.framework.TestSuite; @@ -42,13 +48,13 @@ public class ScheduledExecutorTest exten * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); 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)); + await(done); } } @@ -56,7 +62,7 @@ public class ScheduledExecutorTest exten * delayed schedule of callable successfully executes after delay */ public void testSchedule1() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); @@ -69,7 +75,7 @@ public class ScheduledExecutorTest exten Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); assertSame(Boolean.TRUE, f.get()); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); - assertTrue(done.await(0L, MILLISECONDS)); + assertEquals(0L, done.getCount()); } } @@ -77,7 +83,7 @@ public class ScheduledExecutorTest exten * delayed schedule of runnable successfully executes after delay */ public void testSchedule3() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); @@ -97,7 +103,7 @@ public class ScheduledExecutorTest exten * scheduleAtFixedRate executes runnable after given initial delay */ public void testSchedule4() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); @@ -119,7 +125,7 @@ public class ScheduledExecutorTest exten * scheduleWithFixedDelay executes runnable after given initial delay */ public void testSchedule5() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); @@ -143,54 +149,77 @@ public class ScheduledExecutorTest exten } /** - * scheduleAtFixedRate executes series of tasks at given rate + * scheduleAtFixedRate executes series of tasks at given rate. + * Eventually, it must hold that: + * cycles - 1 <= elapsedMillis/delay < cycles */ public void testFixedRateSequence() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { - long startTime = System.nanoTime(); - int cycles = 10; + final long startTime = System.nanoTime(); + final int cycles = 8; final CountDownLatch done = new CountDownLatch(cycles); - Runnable task = new CheckedRunnable() { + final Runnable task = new CheckedRunnable() { public void realRun() { done.countDown(); }}; - ScheduledFuture h = + final ScheduledFuture periodicTask = p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS); - done.await(); - h.cancel(true); - double normalizedTime = - (double) millisElapsedSince(startTime) / delay; - if (normalizedTime >= cycles - 1 && - normalizedTime <= cycles) + final int totalDelayMillis = (cycles - 1) * delay; + await(done, totalDelayMillis + LONG_DELAY_MS); + periodicTask.cancel(true); + final long elapsedMillis = millisElapsedSince(startTime); + assertTrue(elapsedMillis >= totalDelayMillis); + if (elapsedMillis <= cycles * delay) return; + // else retry with longer delay } - throw new AssertionError("unexpected execution rate"); + fail("unexpected execution rate"); } } /** - * scheduleWithFixedDelay executes series of tasks with given period + * scheduleWithFixedDelay executes series of tasks with given period. + * Eventually, it must hold that each task starts at least delay and at + * most 2 * delay after the termination of the previous task. */ public void testFixedDelaySequence() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { - long startTime = System.nanoTime(); - int cycles = 10; + final long startTime = System.nanoTime(); + final AtomicLong previous = new AtomicLong(startTime); + final AtomicBoolean tryLongerDelay = new AtomicBoolean(false); + final int cycles = 8; final CountDownLatch done = new CountDownLatch(cycles); - Runnable task = new CheckedRunnable() { - public void realRun() { done.countDown(); }}; - ScheduledFuture h = + final int d = delay; + final Runnable task = new CheckedRunnable() { + public void realRun() { + long now = System.nanoTime(); + long elapsedMillis + = NANOSECONDS.toMillis(now - previous.get()); + if (done.getCount() == cycles) { // first execution + if (elapsedMillis >= d) + tryLongerDelay.set(true); + } else { + assertTrue(elapsedMillis >= d); + if (elapsedMillis >= 2 * d) + tryLongerDelay.set(true); + } + previous.set(now); + done.countDown(); + }}; + final ScheduledFuture periodicTask = p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS); - done.await(); - h.cancel(true); - double normalizedTime = - (double) millisElapsedSince(startTime) / delay; - if (normalizedTime >= cycles - 1 && - normalizedTime <= cycles) + final int totalDelayMillis = (cycles - 1) * delay; + await(done, totalDelayMillis + cycles * LONG_DELAY_MS); + periodicTask.cancel(true); + final long elapsedMillis = millisElapsedSince(startTime); + assertTrue(elapsedMillis >= totalDelayMillis); + if (!tryLongerDelay.get()) return; + // else retry with longer delay } - throw new AssertionError("unexpected execution rate"); + fail("unexpected execution rate"); } } @@ -198,7 +227,7 @@ public class ScheduledExecutorTest exten * execute(null) throws NPE */ public void testExecuteNull() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.execute(null); @@ -214,8 +243,8 @@ public class ScheduledExecutorTest exten final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { - TrackedCallable callable = null; - Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS); + Future f = p.schedule((Callable)null, + randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } @@ -225,12 +254,12 @@ public class ScheduledExecutorTest exten * execute throws RejectedExecutionException if shutdown */ public void testSchedule1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); p.schedule(new NoOpRunnable(), - MEDIUM_DELAY_MS, MILLISECONDS); + randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (RejectedExecutionException success) { } catch (SecurityException ok) {} @@ -241,12 +270,12 @@ public class ScheduledExecutorTest exten * schedule throws RejectedExecutionException if shutdown */ public void testSchedule2_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); p.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, MILLISECONDS); + randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (RejectedExecutionException success) { } catch (SecurityException ok) {} @@ -257,12 +286,12 @@ public class ScheduledExecutorTest exten * schedule callable throws RejectedExecutionException if shutdown */ public void testSchedule3_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); p.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, MILLISECONDS); + randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (RejectedExecutionException success) { } catch (SecurityException ok) {} @@ -273,7 +302,7 @@ public class ScheduledExecutorTest exten * scheduleAtFixedRate throws RejectedExecutionException if shutdown */ public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); @@ -289,7 +318,7 @@ public class ScheduledExecutorTest exten * scheduleWithFixedDelay throws RejectedExecutionException if shutdown */ public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); @@ -306,20 +335,19 @@ public class ScheduledExecutorTest exten * thread becomes active */ public void testGetActiveCount() throws InterruptedException { + final CountDownLatch done = new CountDownLatch(1); final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); - 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(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getActiveCount()); - done.countDown(); } } @@ -338,13 +366,13 @@ public class ScheduledExecutorTest exten 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) @@ -373,18 +401,17 @@ public class ScheduledExecutorTest exten final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS); final CountDownLatch threadsStarted = new CountDownLatch(THREADS); final CountDownLatch done = new CountDownLatch(1); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { assertEquals(0, p.getLargestPoolSize()); 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(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadsStarted); assertEquals(THREADS, p.getLargestPoolSize()); - done.countDown(); } assertEquals(THREADS, p.getLargestPoolSize()); } @@ -397,17 +424,16 @@ public class ScheduledExecutorTest exten final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { assertEquals(0, p.getPoolSize()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); assertEquals(1, p.getPoolSize()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getPoolSize()); - done.countDown(); } } @@ -426,9 +452,9 @@ public class ScheduledExecutorTest exten 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++) { @@ -437,7 +463,7 @@ public class ScheduledExecutorTest exten public void realRun() throws InterruptedException { threadStarted.countDown(); assertEquals(1 + TASKS, p.getTaskCount()); - done.await(); + await(done); }}); } assertEquals(1 + TASKS, p.getTaskCount()); @@ -464,7 +490,7 @@ public class ScheduledExecutorTest exten */ public void testSetThreadFactory() throws InterruptedException { ThreadFactory threadFactory = new SimpleThreadFactory(); - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { p.setThreadFactory(threadFactory); assertSame(threadFactory, p.getThreadFactory()); @@ -475,7 +501,7 @@ public class ScheduledExecutorTest exten * setThreadFactory(null) throws NPE */ public void testSetThreadFactoryNull() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.setThreadFactory(null); @@ -485,18 +511,28 @@ public class ScheduledExecutorTest exten } /** + * The default rejected execution handler is AbortPolicy. + */ + public void testDefaultRejectedExecutionHandler() { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertTrue(p.getRejectedExecutionHandler() + instanceof ThreadPoolExecutor.AbortPolicy); + } + } + + /** * isShutdown is false before shutdown, true after */ public void testIsShutdown() { - - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - try { - assertFalse(p.isShutdown()); - } - finally { - try { p.shutdown(); } catch (SecurityException ok) { return; } + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + assertFalse(p.isShutdown()); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + assertTrue(p.isShutdown()); + } catch (SecurityException ok) {} } - assertTrue(p.isShutdown()); } /** @@ -512,9 +548,9 @@ public class ScheduledExecutorTest exten public void realRun() throws InterruptedException { assertFalse(p.isTerminated()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } @@ -536,9 +572,9 @@ public class ScheduledExecutorTest exten public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } @@ -552,24 +588,23 @@ public class ScheduledExecutorTest exten * getQueue returns the work queue, which contains queued tasks */ public void testGetQueue() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch done = new CountDownLatch(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, done)) { final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); ScheduledFuture[] tasks = new ScheduledFuture[5]; for (int i = 0; i < tasks.length; i++) { Runnable r = new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); }}; tasks[i] = p.schedule(r, 1, MILLISECONDS); } - assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); BlockingQueue q = p.getQueue(); assertTrue(q.contains(tasks[tasks.length - 1])); assertFalse(q.contains(tasks[0])); - done.countDown(); } } @@ -577,20 +612,20 @@ public class ScheduledExecutorTest exten * remove(task) removes queued task, and fails to remove active task */ public void testRemove() throws InterruptedException { + final CountDownLatch done = new CountDownLatch(1); final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - try (PoolCleaner cleaner = cleaner(p)) { + try (PoolCleaner cleaner = cleaner(p, done)) { ScheduledFuture[] tasks = new ScheduledFuture[5]; final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); for (int i = 0; i < tasks.length; i++) { Runnable r = new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); - done.await(); + await(done); }}; tasks[i] = p.schedule(r, 1, MILLISECONDS); } - assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS)); + await(threadStarted); BlockingQueue q = p.getQueue(); assertFalse(p.remove((Runnable)tasks[0])); assertTrue(q.contains((Runnable)tasks[4])); @@ -601,7 +636,6 @@ public class ScheduledExecutorTest exten assertTrue(q.contains((Runnable)tasks[3])); assertTrue(p.remove((Runnable)tasks[3])); assertFalse(q.contains((Runnable)tasks[3])); - done.countDown(); } } @@ -654,7 +688,7 @@ public class ScheduledExecutorTest exten }}; 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; @@ -677,7 +711,7 @@ public class ScheduledExecutorTest exten * and those tasks are drained from the queue */ public void testShutdownNow_delayedTasks() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); List tasks = new ArrayList<>(); for (int i = 0; i < 3; i++) { Runnable r = new NoOpRunnable(); @@ -714,91 +748,186 @@ public class ScheduledExecutorTest exten * - setContinueExistingPeriodicTasksAfterShutdownPolicy */ public void testShutdown_cancellation() throws Exception { - Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE }; - for (Boolean policy : allBooleans) - { - final int poolSize = 2; + final int poolSize = 4; final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(poolSize); - final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE); - final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE); - final boolean effectiveRemovePolicy = (policy == Boolean.TRUE); - if (policy != null) { - p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy); - p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy); - p.setRemoveOnCancelPolicy(policy); - } + final BlockingQueue q = p.getQueue(); + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); + final long delay = rnd.nextInt(2); + final int rounds = rnd.nextInt(1, 3); + final boolean effectiveDelayedPolicy; + final boolean effectivePeriodicPolicy; + final boolean effectiveRemovePolicy; + + if (rnd.nextBoolean()) + p.setExecuteExistingDelayedTasksAfterShutdownPolicy( + effectiveDelayedPolicy = rnd.nextBoolean()); + else + effectiveDelayedPolicy = true; assertEquals(effectiveDelayedPolicy, p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); + + if (rnd.nextBoolean()) + p.setContinueExistingPeriodicTasksAfterShutdownPolicy( + effectivePeriodicPolicy = rnd.nextBoolean()); + else + effectivePeriodicPolicy = false; assertEquals(effectivePeriodicPolicy, p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); + + if (rnd.nextBoolean()) + p.setRemoveOnCancelPolicy( + effectiveRemovePolicy = rnd.nextBoolean()); + else + effectiveRemovePolicy = false; assertEquals(effectiveRemovePolicy, p.getRemoveOnCancelPolicy()); - // Strategy: Wedge the pool with poolSize "blocker" threads + + final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean(); + + // Strategy: Wedge the pool with one wave of "blocker" tasks, + // then add a second wave that waits in the queue until unblocked. final AtomicInteger ran = new AtomicInteger(0); final CountDownLatch poolBlocked = new CountDownLatch(poolSize); final CountDownLatch unblock = new CountDownLatch(1); - final CountDownLatch periodicLatch1 = new CountDownLatch(2); - final CountDownLatch periodicLatch2 = new CountDownLatch(2); - Runnable task = new CheckedRunnable() { public void realRun() - throws InterruptedException { - poolBlocked.countDown(); - assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS)); - ran.getAndIncrement(); - }}; - List> blockers = new ArrayList<>(); - List> periodics = new ArrayList<>(); - List> delayeds = new ArrayList<>(); - for (int i = 0; i < poolSize; i++) - blockers.add(p.submit(task)); - assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS)); - - periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1), - 1, 1, MILLISECONDS)); - periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2), - 1, 1, MILLISECONDS)); - delayeds.add(p.schedule(task, 1, MILLISECONDS)); + final RuntimeException exception = new RuntimeException(); - assertTrue(p.getQueue().containsAll(periodics)); - assertTrue(p.getQueue().containsAll(delayeds)); - try { p.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p.isShutdown()); - assertFalse(p.isTerminated()); - for (Future periodic : periodics) { - assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled()); - assertTrue(effectivePeriodicPolicy ^ periodic.isDone()); - } - for (Future delayed : delayeds) { - assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled()); - assertTrue(effectiveDelayedPolicy ^ delayed.isDone()); - } - if (testImplementationDetails) { - assertEquals(effectivePeriodicPolicy, - p.getQueue().containsAll(periodics)); - assertEquals(effectiveDelayedPolicy, - p.getQueue().containsAll(delayeds)); - } - // Release all pool threads - unblock.countDown(); - - for (Future delayed : delayeds) { - if (effectiveDelayedPolicy) { - assertNull(delayed.get()); + class Task implements Runnable { + public void run() { + try { + ran.getAndIncrement(); + poolBlocked.countDown(); + await(unblock); + } catch (Throwable fail) { threadUnexpectedException(fail); } } } - if (effectivePeriodicPolicy) { - assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS)); - for (Future periodic : periodics) { - assertTrue(periodic.cancel(false)); - assertTrue(periodic.isCancelled()); - assertTrue(periodic.isDone()); + + class PeriodicTask extends Task { + PeriodicTask(int rounds) { this.rounds = rounds; } + int rounds; + public void run() { + if (--rounds == 0) super.run(); + // throw exception to surely terminate this periodic task, + // but in a separate execution and in a detectable way. + if (rounds == -1) throw exception; } } + + Runnable task = new Task(); + + List> immediates = new ArrayList<>(); + List> delayeds = new ArrayList<>(); + List> periodics = new ArrayList<>(); + + immediates.add(p.submit(task)); + delayeds.add(p.schedule(task, delay, MILLISECONDS)); + periodics.add(p.scheduleAtFixedRate( + new PeriodicTask(rounds), delay, 1, MILLISECONDS)); + periodics.add(p.scheduleWithFixedDelay( + new PeriodicTask(rounds), delay, 1, MILLISECONDS)); + + await(poolBlocked); + + assertEquals(poolSize, ran.get()); + assertEquals(poolSize, p.getActiveCount()); + assertTrue(q.isEmpty()); + + // Add second wave of tasks. + immediates.add(p.submit(task)); + delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS)); + periodics.add(p.scheduleAtFixedRate( + new PeriodicTask(rounds), delay, 1, MILLISECONDS)); + periodics.add(p.scheduleWithFixedDelay( + new PeriodicTask(rounds), delay, 1, MILLISECONDS)); + + assertEquals(poolSize, q.size()); + assertEquals(poolSize, ran.get()); + + immediates.forEach( + f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L)); + + Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream()) + .forEach(f -> assertFalse(f.isDone())); + + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.isShutdown()); + assertTrue(p.isTerminating()); + assertFalse(p.isTerminated()); + + if (rnd.nextBoolean()) + assertThrows( + RejectedExecutionException.class, + () -> p.submit(task), + () -> p.schedule(task, 1, SECONDS), + () -> p.scheduleAtFixedRate( + new PeriodicTask(1), 1, 1, SECONDS), + () -> p.scheduleWithFixedDelay( + new PeriodicTask(2), 1, 1, SECONDS)); + + assertTrue(q.contains(immediates.get(1))); + assertTrue(!effectiveDelayedPolicy + ^ q.contains(delayeds.get(1))); + assertTrue(!effectivePeriodicPolicy + ^ q.containsAll(periodics.subList(2, 4))); + + immediates.forEach(f -> assertFalse(f.isDone())); + + assertFalse(delayeds.get(0).isDone()); + if (effectiveDelayedPolicy) + assertFalse(delayeds.get(1).isDone()); + else + assertTrue(delayeds.get(1).isCancelled()); + + if (effectivePeriodicPolicy) + periodics.forEach( + f -> { + assertFalse(f.isDone()); + if (!periodicTasksContinue) { + assertTrue(f.cancel(false)); + assertTrue(f.isCancelled()); + } + }); + else { + periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone())); + periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled())); + } + + unblock.countDown(); // Release all pool threads + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertFalse(p.isTerminating()); assertTrue(p.isTerminated()); - assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get()); - }} + + assertTrue(q.isEmpty()); + + Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream()) + .forEach(f -> assertTrue(f.isDone())); + + for (Future f : immediates) assertNull(f.get()); + + assertNull(delayeds.get(0).get()); + if (effectiveDelayedPolicy) + assertNull(delayeds.get(1).get()); + else + assertTrue(delayeds.get(1).isCancelled()); + + if (periodicTasksContinue) + periodics.forEach( + f -> { + try { f.get(); } + catch (ExecutionException success) { + assertSame(exception, success.getCause()); + } + catch (Throwable fail) { threadUnexpectedException(fail); } + }); + else + periodics.forEach(f -> assertTrue(f.isCancelled())); + + assertEquals(poolSize + 1 + + (effectiveDelayedPolicy ? 1 : 0) + + (periodicTasksContinue ? 2 : 0), + ran.get()); + } /** * completed submit of callable returns result @@ -837,7 +966,7 @@ public class ScheduledExecutorTest exten } /** - * invokeAny(null) throws NPE + * invokeAny(null) throws NullPointerException */ public void testInvokeAny1() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); @@ -850,7 +979,7 @@ public class ScheduledExecutorTest exten } /** - * invokeAny(empty collection) throws IAE + * invokeAny(empty collection) throws IllegalArgumentException */ public void testInvokeAny2() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); @@ -863,13 +992,13 @@ public class ScheduledExecutorTest exten } /** - * invokeAny(c) throws NPE if c has null elements + * invokeAny(c) throws NullPointerException if c has null elements */ public void testInvokeAny3() throws Exception { CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -886,7 +1015,7 @@ public class ScheduledExecutorTest exten public void testInvokeAny4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -903,7 +1032,7 @@ public class ScheduledExecutorTest exten public void testInvokeAny5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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); @@ -925,12 +1054,14 @@ public class ScheduledExecutorTest exten } /** - * invokeAll(empty collection) returns empty collection + * invokeAll(empty collection) returns empty list */ public void testInvokeAll2() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); + final Collection> emptyCollection + = Collections.emptyList(); try (PoolCleaner cleaner = cleaner(e)) { - List> r = e.invokeAll(new ArrayList>()); + List> r = e.invokeAll(emptyCollection); assertTrue(r.isEmpty()); } } @@ -941,7 +1072,7 @@ public class ScheduledExecutorTest exten public void testInvokeAll3() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -957,7 +1088,7 @@ public class ScheduledExecutorTest exten public void testInvokeAll4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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()); @@ -976,7 +1107,7 @@ public class ScheduledExecutorTest exten public void testInvokeAll5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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); @@ -993,35 +1124,37 @@ public class ScheduledExecutorTest exten final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { try { - e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAny(null, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } } /** - * timed invokeAny(,,null) throws NPE + * timed invokeAny(,,null) throws NullPointerException */ public void testTimedInvokeAnyNullTimeUnit() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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 = new ScheduledThreadPoolExecutor(2); + final Collection> emptyCollection + = Collections.emptyList(); try (PoolCleaner cleaner = cleaner(e)) { try { - e.invokeAny(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (IllegalArgumentException success) {} } @@ -1034,11 +1167,11 @@ public class ScheduledExecutorTest exten CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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(); @@ -1051,14 +1184,16 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAny4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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); } } @@ -1068,11 +1203,13 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAny5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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); } } @@ -1083,7 +1220,7 @@ public class ScheduledExecutorTest exten final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { try { - e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); + e.invokeAll(null, randomTimeout(), randomTimeUnit()); shouldThrow(); } catch (NullPointerException success) {} } @@ -1095,23 +1232,25 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAllNullTimeUnit() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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 Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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()); } } @@ -1122,11 +1261,11 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAll3() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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) {} } @@ -1138,10 +1277,10 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAll4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); 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(); @@ -1158,7 +1297,7 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAll5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = @@ -1173,16 +1312,22 @@ public class ScheduledExecutorTest exten * timed invokeAll(c) cancels tasks not completed by timeout */ public void testTimedInvokeAll6() throws Exception { - final ExecutorService e = new ScheduledThreadPoolExecutor(2); - 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 ScheduledThreadPoolExecutor(2); + 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) @@ -1201,4 +1346,27 @@ public class ScheduledExecutorTest exten } } + /** + * A fixed delay task with overflowing period should not prevent a + * one-shot task from executing. + * https://bugs.openjdk.java.net/browse/JDK-8051859 + */ + public void testScheduleWithFixedDelay_overflow() throws Exception { + final CountDownLatch delayedDone = new CountDownLatch(1); + final CountDownLatch immediateDone = new CountDownLatch(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final Runnable immediate = new Runnable() { public void run() { + immediateDone.countDown(); + }}; + final Runnable delayed = new Runnable() { public void run() { + delayedDone.countDown(); + p.submit(immediate); + }}; + p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS); + await(delayedDone); + await(immediateDone); + } + } + }