--- jsr166/src/test/tck/ScheduledExecutorTest.java 2009/12/01 22:51:44 1.29 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2018/01/08 02:04:15 1.96 @@ -1,423 +1,567 @@ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/licenses/publicdomain + * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ -import 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.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; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +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; 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); } - /** * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { - TrackedShortRunnable runnable =new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.execute(runnable); - assertFalse(runnable.done); - Thread.sleep(SHORT_DELAY_MS); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - joinPool(p1); + 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); + await(done); + } } - /** * delayed schedule of callable successfully executes after delay */ public void testSchedule1() throws Exception { - TrackedCallable callable = new TrackedCallable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS); - assertFalse(callable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(callable.done); - assertEquals(Boolean.TRUE, f.get()); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - joinPool(p1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final long startTime = System.nanoTime(); + final CountDownLatch done = new CountDownLatch(1); + Callable task = new CheckedCallable() { + public Boolean realCall() { + done.countDown(); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + return Boolean.TRUE; + }}; + Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); + assertSame(Boolean.TRUE, f.get()); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + assertEquals(0L, done.getCount()); + } } /** - * delayed schedule of runnable successfully executes after delay - */ - public void testSchedule3() throws InterruptedException { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.schedule(runnable, SMALL_DELAY_MS, MILLISECONDS); - Thread.sleep(SHORT_DELAY_MS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - joinPool(p1); + * delayed schedule of runnable successfully executes after delay + */ + public void testSchedule3() throws Exception { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final long startTime = System.nanoTime(); + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() { + done.countDown(); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + }}; + Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); + await(done); + assertNull(f.get(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + } } /** * scheduleAtFixedRate executes runnable after given initial delay */ - public void testSchedule4() throws InterruptedException { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - h.cancel(true); - joinPool(p1); - } - - static class RunnableCounter implements Runnable { - AtomicInteger count = new AtomicInteger(0); - public void run() { count.getAndIncrement(); } + public void testSchedule4() throws Exception { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final long startTime = System.nanoTime(); + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() { + done.countDown(); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + }}; + ScheduledFuture f = + p.scheduleAtFixedRate(task, timeoutMillis(), + LONG_DELAY_MS, MILLISECONDS); + await(done); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + f.cancel(true); + } } /** * scheduleWithFixedDelay executes runnable after given initial delay */ - public void testSchedule5() throws InterruptedException { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - h.cancel(true); - joinPool(p1); - } - - /** - * scheduleAtFixedRate executes series of tasks at given rate - */ - public void testFixedRateSequence() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - RunnableCounter counter = new RunnableCounter(); - ScheduledFuture h = - p1.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS); - Thread.sleep(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(p1); - } - - /** - * scheduleWithFixedDelay executes series of tasks with given period - */ - public void testFixedDelaySequence() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - RunnableCounter counter = new RunnableCounter(); - ScheduledFuture h = - p1.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS); - Thread.sleep(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(p1); - } - - - /** - * execute (null) throws NPE - */ - public void testExecuteNull() throws InterruptedException { - ScheduledThreadPoolExecutor se = null; - try { - se = new ScheduledThreadPoolExecutor(1); - se.execute(null); - shouldThrow(); - } catch (NullPointerException success) {} - - joinPool(se); + public void testSchedule5() throws Exception { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final long startTime = System.nanoTime(); + final CountDownLatch done = new CountDownLatch(1); + Runnable task = new CheckedRunnable() { + public void realRun() { + done.countDown(); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + }}; + ScheduledFuture f = + p.scheduleWithFixedDelay(task, timeoutMillis(), + LONG_DELAY_MS, MILLISECONDS); + await(done); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); + f.cancel(true); + } } - /** - * schedule (null) throws NPE - */ - public void testScheduleNull() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - TrackedCallable callable = null; - Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) {} - joinPool(se); + static class RunnableCounter implements Runnable { + AtomicInteger count = new AtomicInteger(0); + public void run() { count.getAndIncrement(); } } /** - * execute throws RejectedExecutionException if shutdown + * scheduleAtFixedRate executes series of tasks at given rate. + * Eventually, it must hold that: + * cycles - 1 <= elapsedMillis/delay < cycles */ - public void testSchedule1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpRunnable(), - MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (RejectedExecutionException success) { - } catch (SecurityException ok) { + public void testFixedRateSequence() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { + final long startTime = System.nanoTime(); + final int cycles = 8; + final CountDownLatch done = new CountDownLatch(cycles); + final Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; + final ScheduledFuture periodicTask = + p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS); + 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 + } + fail("unexpected execution rate"); } - - joinPool(se); } /** - * schedule throws RejectedExecutionException if shutdown + * 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 testSchedule2_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (RejectedExecutionException success) { - } catch (SecurityException ok) { + public void testFixedDelaySequence() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { + 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); + 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); + 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 + } + fail("unexpected execution rate"); } - joinPool(se); } /** - * schedule callable throws RejectedExecutionException if shutdown + * Submitting null tasks throws NullPointerException */ - public void testSchedule3_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (RejectedExecutionException success) { - } catch (SecurityException ok) { + public void testNullTaskSubmission() { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertNullTaskSubmissionThrowsNullPointerException(p); } - joinPool(se); } /** - * scheduleAtFixedRate throws RejectedExecutionException if shutdown - */ - public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.scheduleAtFixedRate(new NoOpRunnable(), - MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (RejectedExecutionException success) { - } catch (SecurityException ok) { - } - joinPool(se); - } + * Submitted tasks are rejected when shutdown + */ + public void testSubmittedTasksRejectedWhenShutdown() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); + final CountDownLatch threadsStarted = new CountDownLatch(p.getCorePoolSize()); + final CountDownLatch done = new CountDownLatch(1); + final Runnable r = () -> { + threadsStarted.countDown(); + for (;;) { + try { + done.await(); + return; + } catch (InterruptedException shutdownNowDeliberatelyIgnored) {} + }}; + final Callable c = () -> { + threadsStarted.countDown(); + for (;;) { + try { + done.await(); + return Boolean.TRUE; + } catch (InterruptedException shutdownNowDeliberatelyIgnored) {} + }}; + + try (PoolCleaner cleaner = cleaner(p, done)) { + for (int i = p.getCorePoolSize(); 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; + } + } - /** - * scheduleWithFixedDelay throws RejectedExecutionException if shutdown - */ - public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.scheduleWithFixedDelay(new NoOpRunnable(), - MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (RejectedExecutionException success) { - } catch (SecurityException ok) { + // ScheduledThreadPoolExecutor has an unbounded queue, so never saturated. + await(threadsStarted); + + if (rnd.nextBoolean()) + 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); } - joinPool(se); + assertEquals(p.getCorePoolSize(), p.getCompletedTaskCount()); } /** - * getActiveCount increases but doesn't overestimate, when a - * thread becomes active + * getActiveCount increases but doesn't overestimate, when a + * thread becomes active */ public void testGetActiveCount() throws InterruptedException { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getActiveCount()); - p2.execute(new SmallRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(1, p2.getActiveCount()); - joinPool(p2); + final CountDownLatch done = new CountDownLatch(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); + 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()); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getActiveCount()); + } } /** - * getCompletedTaskCount increases, but doesn't overestimate, - * when tasks complete + * getCompletedTaskCount increases, but doesn't overestimate, + * when tasks complete */ public void testGetCompletedTaskCount() throws InterruptedException { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getCompletedTaskCount()); - p2.execute(new SmallRunnable()); - Thread.sleep(MEDIUM_DELAY_MS); - assertEquals(1, p2.getCompletedTaskCount()); - joinPool(p2); + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); + 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()); + await(threadProceed); + threadDone.countDown(); + }}); + await(threadStarted); + assertEquals(0, p.getCompletedTaskCount()); + threadProceed.countDown(); + await(threadDone); + long startTime = System.nanoTime(); + while (p.getCompletedTaskCount() != 1) { + if (millisElapsedSince(startTime) > LONG_DELAY_MS) + fail("timed out"); + Thread.yield(); + } + } } /** - * getCorePoolSize returns size given in constructor if not otherwise set + * getCorePoolSize returns size given in constructor if not otherwise set */ public void testGetCorePoolSize() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(1, p1.getCorePoolSize()); - joinPool(p1); + ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getCorePoolSize()); + } } /** - * getLargestPoolSize increases, but doesn't overestimate, when - * multiple threads active + * getLargestPoolSize increases, but doesn't overestimate, when + * multiple threads active */ public void testGetLargestPoolSize() throws InterruptedException { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getLargestPoolSize()); - p2.execute(new SmallRunnable()); - p2.execute(new SmallRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(2, p2.getLargestPoolSize()); - joinPool(p2); + final int THREADS = 3; + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS); + final CountDownLatch threadsStarted = new CountDownLatch(THREADS); + final CountDownLatch done = new CountDownLatch(1); + 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(); + await(done); + assertEquals(THREADS, p.getLargestPoolSize()); + }}); + await(threadsStarted); + assertEquals(THREADS, p.getLargestPoolSize()); + } + assertEquals(THREADS, p.getLargestPoolSize()); } /** - * getPoolSize increases, but doesn't overestimate, when threads - * become active + * getPoolSize increases, but doesn't overestimate, when threads + * become active */ public void testGetPoolSize() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(0, p1.getPoolSize()); - p1.execute(new SmallRunnable()); - assertEquals(1, p1.getPoolSize()); - joinPool(p1); + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + 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()); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getPoolSize()); + } } /** - * getTaskCount increases, but doesn't overestimate, when tasks - * submitted + * getTaskCount increases, but doesn't overestimate, when tasks + * submitted */ public void testGetTaskCount() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(0, p1.getTaskCount()); - for (int i = 0; i < 5; i++) - p1.execute(new SmallRunnable()); - Thread.sleep(SHORT_DELAY_MS); - assertEquals(5, p1.getTaskCount()); - joinPool(p1); + final int TASKS = 3; + final CountDownLatch done = new CountDownLatch(1); + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + assertEquals(0, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertEquals(1, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + for (int i = 0; i < TASKS; i++) { + assertEquals(1 + i, p.getTaskCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1 + TASKS, p.getTaskCount()); + await(done); + }}); + } + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); + } + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(1 + TASKS, p.getCompletedTaskCount()); } /** * getThreadFactory returns factory in constructor if not set */ public void testGetThreadFactory() throws InterruptedException { - ThreadFactory tf = new SimpleThreadFactory(); - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + final ThreadFactory threadFactory = new SimpleThreadFactory(); + final ScheduledThreadPoolExecutor p = + new ScheduledThreadPoolExecutor(1, threadFactory); + try (PoolCleaner cleaner = cleaner(p)) { + assertSame(threadFactory, p.getThreadFactory()); + } } /** * setThreadFactory sets the thread factory returned by getThreadFactory */ public void testSetThreadFactory() throws InterruptedException { - ThreadFactory tf = new SimpleThreadFactory(); - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - p.setThreadFactory(tf); - assertSame(tf, p.getThreadFactory()); - joinPool(p); + ThreadFactory threadFactory = new SimpleThreadFactory(); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + p.setThreadFactory(threadFactory); + assertSame(threadFactory, p.getThreadFactory()); + } } /** * setThreadFactory(null) throws NPE */ public void testSetThreadFactoryNull() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - try { - p.setThreadFactory(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setThreadFactory(null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * is isShutDown is false before shutdown, true after + * The default rejected execution handler is AbortPolicy. */ - public void testIsShutdown() { - - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - try { - assertFalse(p1.isShutdown()); + public void testDefaultRejectedExecutionHandler() { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertTrue(p.getRejectedExecutionHandler() + instanceof ThreadPoolExecutor.AbortPolicy); } - finally { - try { p1.shutdown(); } catch (SecurityException ok) { return; } - } - assertTrue(p1.isShutdown()); } + /** + * isShutdown is false before shutdown, true after + */ + public void testIsShutdown() { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + assertFalse(p.isShutdown()); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + assertTrue(p.isShutdown()); + } catch (SecurityException ok) {} + } + } /** - * isTerminated is false before termination, true after + * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - try { - p1.execute(new SmallRunnable()); - } finally { - try { p1.shutdown(); } catch (SecurityException ok) { return; } + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + assertFalse(p.isTerminated()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminated()); + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertFalse(p.isTerminating()); + done.countDown(); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); } - assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p1.isTerminated()); } /** - * isTerminating is not true when running or when terminated + * isTerminating is not true when running or when terminated */ public void testIsTerminating() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertFalse(p1.isTerminating()); - try { - p1.execute(new SmallRunnable()); - assertFalse(p1.isTerminating()); - } finally { - try { p1.shutdown(); } catch (SecurityException ok) { return; } + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertFalse(p.isTerminating()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + assertFalse(p.isTerminating()); + threadStarted.countDown(); + await(done); + }}); + await(threadStarted); + assertFalse(p.isTerminating()); + done.countDown(); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertFalse(p.isTerminating()); } - - assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p1.isTerminated()); - assertFalse(p1.isTerminating()); } /** * getQueue returns the work queue, which contains queued tasks */ public void testGetQueue() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS); - } - try { - Thread.sleep(SHORT_DELAY_MS); - BlockingQueue q = p1.getQueue(); - assertTrue(q.contains(tasks[4])); + final CountDownLatch done = new CountDownLatch(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = 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(); + await(done); + }}; + tasks[i] = p.schedule(r, 1, MILLISECONDS); + } + await(threadStarted); + BlockingQueue q = p.getQueue(); + assertTrue(q.contains(tasks[tasks.length - 1])); assertFalse(q.contains(tasks[0])); - } finally { - joinPool(p1); } } @@ -425,176 +569,333 @@ public class ScheduledExecutorTest exten * remove(task) removes queued task, and fails to remove active task */ public void testRemove() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS); - } - try { - Thread.sleep(SHORT_DELAY_MS); - BlockingQueue q = p1.getQueue(); - assertFalse(p1.remove((Runnable)tasks[0])); + final CountDownLatch done = new CountDownLatch(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, done)) { + ScheduledFuture[] tasks = new ScheduledFuture[5]; + final CountDownLatch threadStarted = new CountDownLatch(1); + for (int i = 0; i < tasks.length; i++) { + Runnable r = new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + await(done); + }}; + tasks[i] = p.schedule(r, 1, MILLISECONDS); + } + await(threadStarted); + BlockingQueue q = p.getQueue(); + assertFalse(p.remove((Runnable)tasks[0])); assertTrue(q.contains((Runnable)tasks[4])); assertTrue(q.contains((Runnable)tasks[3])); - assertTrue(p1.remove((Runnable)tasks[4])); - assertFalse(p1.remove((Runnable)tasks[4])); + assertTrue(p.remove((Runnable)tasks[4])); + assertFalse(p.remove((Runnable)tasks[4])); assertFalse(q.contains((Runnable)tasks[4])); assertTrue(q.contains((Runnable)tasks[3])); - assertTrue(p1.remove((Runnable)tasks[3])); + assertTrue(p.remove((Runnable)tasks[3])); assertFalse(q.contains((Runnable)tasks[3])); - } finally { - joinPool(p1); } } /** - * purge removes cancelled tasks from the queue + * purge eventually removes cancelled tasks from the queue */ public void testPurge() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < 5; i++) { - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS); - } - try { - int max = 5; + final ScheduledFuture[] tasks = new ScheduledFuture[5]; + final Runnable releaser = new Runnable() { public void run() { + for (ScheduledFuture task : tasks) + if (task != null) task.cancel(true); }}; + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, releaser)) { + for (int i = 0; i < tasks.length; i++) + tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), + LONG_DELAY_MS, MILLISECONDS); + int max = tasks.length; if (tasks[4].cancel(true)) --max; if (tasks[3].cancel(true)) --max; // There must eventually be an interference-free point at // which purge will not fail. (At worst, when queue is empty.) - int k; - for (k = 0; k < SMALL_DELAY_MS; ++k) { - p1.purge(); - long count = p1.getTaskCount(); - if (count >= 0 && count <= max) - break; - Thread.sleep(1); - } - assertTrue(k < SMALL_DELAY_MS); - } finally { - joinPool(p1); + long startTime = System.nanoTime(); + do { + p.purge(); + long count = p.getTaskCount(); + if (count == max) + return; + } while (millisElapsedSince(startTime) < LONG_DELAY_MS); + fail("Purge failed to remove cancelled tasks"); } } /** - * shutDownNow returns a list containing tasks that were not run - */ - public void testShutDownNow() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - for (int i = 0; i < 5; i++) - p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS); - List l; + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue + */ + public void testShutdownNow() throws InterruptedException { + final int poolSize = 2; + final int count = 5; + final AtomicInteger ran = new AtomicInteger(0); + final ScheduledThreadPoolExecutor p = + new ScheduledThreadPoolExecutor(poolSize); + final 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); + await(threadsStarted); + assertEquals(poolSize, p.getActiveCount()); + assertEquals(0, p.getCompletedTaskCount()); + final List queuedTasks; try { - l = p1.shutdownNow(); + queuedTasks = p.shutdownNow(); } catch (SecurityException ok) { - return; + return; // Allowed in case test doesn't have privs } - assertTrue(p1.isShutdown()); - assertTrue(l.size() > 0 && l.size() <= 5); - joinPool(p1); + 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 - */ - public void testShutDown1() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy()); - - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < 5; i++) - tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - BlockingQueue q = p1.getQueue(); - for (Iterator it = q.iterator(); it.hasNext();) { - ScheduledFuture t = (ScheduledFuture)it.next(); - assertFalse(t.isCancelled()); + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue + */ + public void testShutdownNow_delayedTasks() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + 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(p1.isShutdown()); - Thread.sleep(SMALL_DELAY_MS); - for (int i = 0; i < 5; ++i) { - assertTrue(tasks[i].isDone()); - assertFalse(tasks[i].isCancelled()); + assertTrue(p.isShutdown()); + assertTrue(p.getQueue().isEmpty()); + if (testImplementationDetails) + assertEquals(new HashSet(tasks), new HashSet(queuedTasks)); + assertEquals(tasks.size(), queuedTasks.size()); + for (ScheduledFuture task : tasks) { + assertFalse(task.isDone()); + assertFalse(task.isCancelled()); } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); } - /** - * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false, - * delayed tasks are cancelled at shutdown - */ - public void testShutDown2() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < 5; i++) - tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p1.isShutdown()); - BlockingQueue q = p1.getQueue(); + * 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 + */ + @SuppressWarnings("FutureReturnValueIgnored") + public void testShutdown_cancellation() throws Exception { + final int poolSize = 4; + final ScheduledThreadPoolExecutor p + = new ScheduledThreadPoolExecutor(poolSize); + 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()); + + 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 RuntimeException exception = new RuntimeException(); + + class Task implements Runnable { + public void run() { + try { + ran.getAndIncrement(); + poolBlocked.countDown(); + await(unblock); + } catch (Throwable fail) { threadUnexpectedException(fail); } + } + } + + 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()); - Thread.sleep(SMALL_DELAY_MS); - assertTrue(p1.isTerminated()); - } + // 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(Collection::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()); - /** - * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false, - * periodic tasks are not cancelled at shutdown - */ - public void testShutDown3() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - ScheduledFuture task = - p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - assertTrue(p1.isShutdown()); - BlockingQueue q = p1.getQueue(); assertTrue(q.isEmpty()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(p1.isTerminated()); - } - /** - * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true, - * periodic tasks are cancelled at shutdown - */ - public void testShutDown4() throws InterruptedException { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - try { - p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); - ScheduledFuture task = - p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, MILLISECONDS); - assertFalse(task.isCancelled()); - try { p1.shutdown(); } catch (SecurityException ok) { return; } - assertFalse(task.isCancelled()); - assertFalse(p1.isTerminated()); - assertTrue(p1.isShutdown()); - Thread.sleep(SHORT_DELAY_MS); - assertFalse(task.isCancelled()); - assertTrue(task.cancel(true)); - assertTrue(task.isDone()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(p1.isTerminated()); - } - finally { - joinPool(p1); - } + Stream.of(immediates, delayeds, periodics).flatMap(Collection::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 */ public void testSubmitCallable() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new StringTask()); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } @@ -602,13 +903,11 @@ public class ScheduledExecutorTest exten * completed submit of runnable returns successfully */ public void testSubmitRunnable() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable()); future.get(); assertTrue(future.isDone()); - } finally { - joinPool(e); } } @@ -616,60 +915,55 @@ public class ScheduledExecutorTest exten * completed submit of (runnable, result) returns result */ public void testSubmitRunnable2() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { Future future = e.submit(new NoOpRunnable(), TEST_STRING); String result = future.get(); assertSame(TEST_STRING, result); - } finally { - joinPool(e); } } /** - * invokeAny(null) throws NPE + * invokeAny(null) throws NullPointerException */ public void testInvokeAny1() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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 = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(new ArrayList>()); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } /** - * 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); - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(latchAwaitingStringTask(latch)); - l.add(null); - try { - e.invokeAny(l); - shouldThrow(); - } catch (NullPointerException success) { - } finally { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -677,16 +971,16 @@ public class ScheduledExecutorTest exten * invokeAny(c) throws ExecutionException if no task completes */ public void testInvokeAny4() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new NPETask()); - try { - e.invokeAny(l); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); + } } } @@ -694,15 +988,13 @@ public class ScheduledExecutorTest exten * invokeAny(c) returns result of some task */ public void testInvokeAny5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> l = new ArrayList>(); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -710,26 +1002,25 @@ public class ScheduledExecutorTest exten * invokeAll(null) throws NPE */ public void testInvokeAll1() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAll(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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 Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> r = e.invokeAll(new ArrayList>()); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + final Collection> emptyCollection + = Collections.emptyList(); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(emptyCollection); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -737,16 +1028,15 @@ public class ScheduledExecutorTest exten * invokeAll(c) throws NPE if c has null elements */ public void testInvokeAll3() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); - try { - e.invokeAll(l); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new StringTask()); + l.add(null); + try { + e.invokeAll(l); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -754,18 +1044,18 @@ public class ScheduledExecutorTest exten * get of invokeAll(c) throws exception on failed task */ public void testInvokeAll4() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new NPETask()); - List> futures = e.invokeAll(l); - assertEquals(1, futures.size()); - try { - futures.get(0).get(); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList<>(); + l.add(new NPETask()); + List> futures = e.invokeAll(l); + assertEquals(1, futures.size()); + try { + futures.get(0).get(); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } } @@ -773,17 +1063,15 @@ public class ScheduledExecutorTest exten * invokeAll(c) returns results of all completed tasks */ public void testInvokeAll5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> l = new ArrayList>(); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -791,43 +1079,42 @@ public class ScheduledExecutorTest exten * timed invokeAny(null) throws NPE */ public void testTimedInvokeAny1() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * timed invokeAny(,,null) throws NPE + * timed invokeAny(,,null) throws NullPointerException */ public void testTimedInvokeAnyNullTimeUnit() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new StringTask()); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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 = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (IllegalArgumentException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + final Collection> emptyCollection + = Collections.emptyList(); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } @@ -836,17 +1123,16 @@ public class ScheduledExecutorTest exten */ public void testTimedInvokeAny3() throws Exception { CountDownLatch latch = new CountDownLatch(1); - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(latchAwaitingStringTask(latch)); - l.add(null); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -854,16 +1140,18 @@ public class ScheduledExecutorTest exten * timed invokeAny(c) throws ExecutionException if no task completes */ public void testTimedInvokeAny4() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new NPETask()); - try { - e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -871,15 +1159,15 @@ public class ScheduledExecutorTest exten * timed invokeAny(c) returns result of some task */ public void testTimedInvokeAny5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> l = new ArrayList>(); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -887,13 +1175,12 @@ public class ScheduledExecutorTest exten * timed invokeAll(null) throws NPE */ public void testTimedInvokeAll1() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null, randomTimeout(), randomTimeUnit()); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -901,28 +1188,28 @@ public class ScheduledExecutorTest exten * timed invokeAll(,,null) throws NPE */ public void testTimedInvokeAllNullTimeUnit() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new StringTask()); - try { - e.invokeAll(l, MEDIUM_DELAY_MS, null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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 Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> r = e.invokeAll(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + final Collection> emptyCollection + = Collections.emptyList(); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = + e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit()); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -930,16 +1217,15 @@ public class ScheduledExecutorTest exten * timed invokeAll(c) throws NPE if c has null elements */ public void testTimedInvokeAll3() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new StringTask()); - l.add(null); - try { - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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) {} } } @@ -947,19 +1233,19 @@ public class ScheduledExecutorTest exten * get of element of invokeAll(c) throws exception on failed task */ public void testTimedInvokeAll4() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - List> l = new ArrayList>(); - l.add(new NPETask()); - List> futures = - e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); - assertEquals(1, futures.size()); - try { - futures.get(0).get(); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof NullPointerException); - } finally { - joinPool(e); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); + } } } @@ -967,18 +1253,16 @@ public class ScheduledExecutorTest exten * timed invokeAll(c) returns results of all completed tasks */ public void testTimedInvokeAll5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> l = new ArrayList>(); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + 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); } } @@ -986,28 +1270,59 @@ public class ScheduledExecutorTest exten * timed invokeAll(c) cancels tasks not completed by timeout */ 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()); - } finally { - joinPool(e); + 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(waiter); + tasks.add(new StringTask("2")); + long startTime = System.nanoTime(); + List> futures = + p.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"); + } + } } } + /** + * A fixed delay task with overflowing period should not prevent a + * one-shot task from executing. + * https://bugs.openjdk.java.net/browse/JDK-8051859 + */ + @SuppressWarnings("FutureReturnValueIgnored") + 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 delayed = () -> { + delayedDone.countDown(); + p.submit(() -> immediateDone.countDown()); + }; + p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS); + await(delayedDone); + await(immediateDone); + } + } }