--- jsr166/src/test/tck/ScheduledExecutorTest.java 2011/05/28 15:33:20 1.44 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2015/10/03 00:37:31 1.59 @@ -6,15 +6,33 @@ * Pat Fisher, Mike Judd. */ -import junit.framework.*; -import java.util.*; -import java.util.concurrent.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.concurrent.atomic.*; +import static java.util.concurrent.TimeUnit.SECONDS; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; + +import junit.framework.Test; +import junit.framework.TestSuite; public class ScheduledExecutorTest extends JSR166TestCase { public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); + main(suite(), args); } public static Test suite() { return new TestSuite(ScheduledExecutorTest.class); @@ -141,17 +159,27 @@ public class ScheduledExecutorTest exten */ public void testFixedRateSequence() throws InterruptedException { ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - RunnableCounter counter = new RunnableCounter(); - ScheduledFuture h = - p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS); - delay(SMALL_DELAY_MS); - h.cancel(true); - int c = counter.count.get(); - // By time scaling conventions, we must have at least - // an execution per SHORT delay, but no more than one SHORT more - assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS); - assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS); - joinPool(p); + try { + for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { + long startTime = System.nanoTime(); + int cycles = 10; + final CountDownLatch done = new CountDownLatch(cycles); + Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; + ScheduledFuture h = + p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS); + done.await(); + h.cancel(true); + double normalizedTime = + (double) millisElapsedSince(startTime) / delay; + if (normalizedTime >= cycles - 1 && + normalizedTime <= cycles) + return; + } + throw new AssertionError("unexpected execution rate"); + } finally { + joinPool(p); + } } /** @@ -159,15 +187,27 @@ public class ScheduledExecutorTest exten */ public void testFixedDelaySequence() throws InterruptedException { ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - RunnableCounter counter = new RunnableCounter(); - ScheduledFuture h = - p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS); - delay(SMALL_DELAY_MS); - h.cancel(true); - int c = counter.count.get(); - assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS); - assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS); - joinPool(p); + try { + for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { + long startTime = System.nanoTime(); + int cycles = 10; + final CountDownLatch done = new CountDownLatch(cycles); + Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; + ScheduledFuture h = + p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS); + done.await(); + h.cancel(true); + double normalizedTime = + (double) millisElapsedSince(startTime) / delay; + if (normalizedTime >= cycles - 1 && + normalizedTime <= cycles) + return; + } + throw new AssertionError("unexpected execution rate"); + } finally { + joinPool(p); + } } /** @@ -320,7 +360,7 @@ public class ScheduledExecutorTest exten threadProceed.await(); threadDone.countDown(); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(0, p.getCompletedTaskCount()); threadProceed.countDown(); threadDone.await(); @@ -613,137 +653,170 @@ public class ScheduledExecutorTest exten } /** - * shutdownNow returns a list containing tasks that were not run + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue */ - public void testShutdownNow() { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - for (int i = 0; i < 5; i++) - p.schedule(new SmallPossiblyInterruptedRunnable(), - LONG_DELAY_MS, MILLISECONDS); - try { - List l = p.shutdownNow(); - assertTrue(p.isShutdown()); - assertEquals(5, l.size()); + public void testShutdownNow() throws InterruptedException { + final int poolSize = 2; + final int count = 5; + final AtomicInteger ran = new AtomicInteger(0); + final ScheduledThreadPoolExecutor p = + new ScheduledThreadPoolExecutor(poolSize); + CountDownLatch threadsStarted = new CountDownLatch(poolSize); + Runnable waiter = new CheckedRunnable() { public void realRun() { + threadsStarted.countDown(); + try { + MILLISECONDS.sleep(2 * LONG_DELAY_MS); + } catch (InterruptedException success) {} + ran.getAndIncrement(); + }}; + for (int i = 0; i < count; i++) + p.execute(waiter); + assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(poolSize, p.getActiveCount()); + assertEquals(0, p.getCompletedTaskCount()); + final List queuedTasks; + try { + queuedTasks = p.shutdownNow(); } catch (SecurityException ok) { - // Allowed in case test doesn't have privs - } finally { - joinPool(p); + return; // Allowed in case test doesn't have privs } + assertTrue(p.isShutdown()); + assertTrue(p.getQueue().isEmpty()); + assertEquals(count - poolSize, queuedTasks.size()); + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertEquals(poolSize, ran.get()); + assertEquals(poolSize, p.getCompletedTaskCount()); } /** - * In default setting, shutdown cancels periodic but not delayed - * tasks at shutdown + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue */ - public void testShutdown1() throws InterruptedException { + public void testShutdownNow_delayedTasks() throws InterruptedException { ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < tasks.length; i++) - tasks[i] = p.schedule(new NoOpRunnable(), - SHORT_DELAY_MS, MILLISECONDS); - try { p.shutdown(); } catch (SecurityException ok) { return; } - BlockingQueue q = p.getQueue(); - for (ScheduledFuture task : tasks) { - assertFalse(task.isDone()); - assertFalse(task.isCancelled()); - assertTrue(q.contains(task)); + List tasks = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + Runnable r = new NoOpRunnable(); + tasks.add(p.schedule(r, 9, SECONDS)); + tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS)); + tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS)); + } + if (testImplementationDetails) + assertEquals(new HashSet(tasks), new HashSet(p.getQueue())); + final List queuedTasks; + try { + queuedTasks = p.shutdownNow(); + } catch (SecurityException ok) { + return; // Allowed in case test doesn't have privs } assertTrue(p.isShutdown()); - assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); + assertTrue(p.getQueue().isEmpty()); + if (testImplementationDetails) + assertEquals(new HashSet(tasks), new HashSet(queuedTasks)); + assertEquals(tasks.size(), queuedTasks.size()); for (ScheduledFuture task : tasks) { - assertTrue(task.isDone()); + assertFalse(task.isDone()); assertFalse(task.isCancelled()); } - } - - /** - * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false, - * delayed tasks are cancelled at shutdown - */ - public void testShutdown2() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < tasks.length; i++) - tasks[i] = p.schedule(new NoOpRunnable(), - SHORT_DELAY_MS, MILLISECONDS); - BlockingQueue q = p.getQueue(); - assertEquals(tasks.length, q.size()); - try { p.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p.isShutdown()); - assertTrue(q.isEmpty()); - assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS)); + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); - for (ScheduledFuture task : tasks) { - assertTrue(task.isDone()); - assertTrue(task.isCancelled()); - } } /** - * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false, - * periodic tasks are cancelled at shutdown - */ - public void testShutdown3() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - long initialDelay = LONG_DELAY_MS; - ScheduledFuture task = - p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay, - 5, MILLISECONDS); + * By default, periodic tasks are cancelled at shutdown. + * By default, delayed tasks keep running after shutdown. + * Check that changing the default values work: + * - setExecuteExistingDelayedTasksAfterShutdownPolicy + * - setContinueExistingPeriodicTasksAfterShutdownPolicy + */ + public void testShutdown_cancellation() throws Exception { + Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE }; + for (Boolean policy : allBooleans) + { + final int poolSize = 2; + 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); + } + assertEquals(effectiveDelayedPolicy, + p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); + assertEquals(effectivePeriodicPolicy, + p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); + assertEquals(effectiveRemovePolicy, + p.getRemoveOnCancelPolicy()); + // Strategy: Wedge the pool with poolSize "blocker" threads + 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)); + + assertTrue(p.getQueue().containsAll(periodics)); + assertTrue(p.getQueue().containsAll(delayeds)); try { p.shutdown(); } catch (SecurityException ok) { return; } assertTrue(p.isShutdown()); - assertTrue(p.getQueue().isEmpty()); - assertTrue(task.isDone()); - assertTrue(task.isCancelled()); - joinPool(p); - } - - /** - * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true, - * periodic tasks are not cancelled at shutdown - */ - public void testShutdown4() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final CountDownLatch counter = new CountDownLatch(2); - try { - p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); - assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - final Runnable r = new CheckedRunnable() { - public void realRun() { - counter.countDown(); - }}; - ScheduledFuture task = - p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS); - assertFalse(task.isDone()); - assertFalse(task.isCancelled()); - try { p.shutdown(); } catch (SecurityException ok) { return; } - assertFalse(task.isCancelled()); - assertFalse(p.isTerminated()); - assertTrue(p.isShutdown()); - assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS)); - assertFalse(task.isCancelled()); - assertTrue(task.cancel(false)); - assertTrue(task.isDone()); - assertTrue(task.isCancelled()); - assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); + 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()); + } } - finally { - joinPool(p); + 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()); + } } - } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get()); + }} /** * completed submit of callable returns result @@ -1134,7 +1207,7 @@ public class ScheduledExecutorTest exten 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()); @@ -1149,22 +1222,29 @@ public class ScheduledExecutorTest exten public void testTimedInvokeAll6() throws Exception { ExecutorService e = new ScheduledThreadPoolExecutor(2); try { - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING)); - l.add(new StringTask()); - List> futures = - e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS); - assertEquals(3, futures.size()); - Iterator> it = futures.iterator(); - Future f1 = it.next(); - Future f2 = it.next(); - Future f3 = it.next(); - assertTrue(f1.isDone()); - assertTrue(f2.isDone()); - assertTrue(f3.isDone()); - assertFalse(f1.isCancelled()); - assertTrue(f2.isCancelled()); + for (long timeout = timeoutMillis();;) { + List> tasks = new ArrayList<>(); + tasks.add(new StringTask("0")); + tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING)); + tasks.add(new StringTask("2")); + long startTime = System.nanoTime(); + List> futures = + e.invokeAll(tasks, timeout, MILLISECONDS); + assertEquals(tasks.size(), futures.size()); + assertTrue(millisElapsedSince(startTime) >= timeout); + for (Future future : futures) + assertTrue(future.isDone()); + assertTrue(futures.get(1).isCancelled()); + try { + assertEquals("0", futures.get(0).get()); + assertEquals("2", futures.get(2).get()); + break; + } catch (CancellationException retryWithLongerTimeout) { + timeout *= 2; + if (timeout >= LONG_DELAY_MS / 2) + fail("expected exactly one task to be cancelled"); + } + } } finally { joinPool(e); }