--- jsr166/src/test/tck/ScheduledExecutorTest.java 2011/05/07 19:34:51 1.40 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2015/10/08 03:08:37 1.76 @@ -6,61 +6,70 @@ * 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); } - /** * execute successfully executes a runnable */ public void testExecute() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final CountDownLatch done = new CountDownLatch(1); - final Runnable task = new CheckedRunnable() { - public void realRun() { - done.countDown(); - }}; - try { + 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)); - } finally { - joinPool(p); + assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS)); } } - /** * delayed schedule of callable successfully executes after delay */ public void testSchedule1() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final long t0 = System.nanoTime(); - final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L; - final CountDownLatch done = new CountDownLatch(1); - try { + 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(System.nanoTime() - t0 >= timeoutNanos); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); return Boolean.TRUE; }}; - Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS); - assertEquals(Boolean.TRUE, f.get()); - assertTrue(System.nanoTime() - t0 >= timeoutNanos); + Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); + assertSame(Boolean.TRUE, f.get()); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); assertTrue(done.await(0L, MILLISECONDS)); - } finally { - joinPool(p); } } @@ -68,22 +77,19 @@ public class ScheduledExecutorTest exten * delayed schedule of runnable successfully executes after delay */ public void testSchedule3() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final long t0 = System.nanoTime(); - final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L; - final CountDownLatch done = new CountDownLatch(1); - try { + 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(System.nanoTime() - t0 >= timeoutNanos); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); }}; - Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS); - assertNull(f.get()); - assertTrue(System.nanoTime() - t0 >= timeoutNanos); - assertTrue(done.await(0L, MILLISECONDS)); - } finally { - joinPool(p); + Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); + await(done); + assertNull(f.get(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); } } @@ -91,49 +97,43 @@ public class ScheduledExecutorTest exten * scheduleAtFixedRate executes runnable after given initial delay */ public void testSchedule4() throws Exception { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final long t0 = System.nanoTime(); - final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L; - final CountDownLatch done = new CountDownLatch(1); - try { + 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(System.nanoTime() - t0 >= timeoutNanos); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); }}; ScheduledFuture f = - p.scheduleAtFixedRate(task, SHORT_DELAY_MS, - SHORT_DELAY_MS, MILLISECONDS); - assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS)); - assertTrue(System.nanoTime() - t0 >= timeoutNanos); + p.scheduleAtFixedRate(task, timeoutMillis(), + LONG_DELAY_MS, MILLISECONDS); + await(done); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); f.cancel(true); - } finally { - joinPool(p); } } /** * scheduleWithFixedDelay executes runnable after given initial delay */ - public void testSchedule5() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final long t0 = System.nanoTime(); - final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L; - final CountDownLatch done = new CountDownLatch(1); - try { + 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(System.nanoTime() - t0 >= timeoutNanos); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); }}; ScheduledFuture f = - p.scheduleWithFixedDelay(task, SHORT_DELAY_MS, - SHORT_DELAY_MS, MILLISECONDS); - assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS)); - assertTrue(System.nanoTime() - t0 >= timeoutNanos); + p.scheduleWithFixedDelay(task, timeoutMillis(), + LONG_DELAY_MS, MILLISECONDS); + await(done); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); f.cancel(true); - } finally { - joinPool(p); } } @@ -146,143 +146,159 @@ public class ScheduledExecutorTest exten * scheduleAtFixedRate executes series of tasks at given rate */ 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); + 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 CountDownLatch done = new CountDownLatch(cycles); + Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; + ScheduledFuture h = + p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS); + await(done); + h.cancel(true); + double normalizedTime = + (double) millisElapsedSince(startTime) / delay; + if (normalizedTime >= cycles - 1 && + normalizedTime <= cycles) + return; + } + throw new AssertionError("unexpected execution rate"); + } } /** * scheduleWithFixedDelay executes series of tasks with given period */ 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); + 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 CountDownLatch done = new CountDownLatch(cycles); + Runnable task = new CheckedRunnable() { + public void realRun() { done.countDown(); }}; + ScheduledFuture h = + p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS); + await(done); + h.cancel(true); + double normalizedTime = + (double) millisElapsedSince(startTime) / delay; + if (normalizedTime >= cycles - 1 && + normalizedTime <= cycles) + return; + } + throw new AssertionError("unexpected execution rate"); + } } - /** * 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); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.execute(null); + shouldThrow(); + } catch (NullPointerException success) {} + } } /** * 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); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + TrackedCallable callable = null; + Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} + } } /** * execute throws RejectedExecutionException if shutdown */ 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) { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + p.schedule(new NoOpRunnable(), + MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (RejectedExecutionException success) { + } catch (SecurityException ok) {} } - - joinPool(se); } /** * schedule throws RejectedExecutionException if shutdown */ 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) { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + p.schedule(new NoOpCallable(), + MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (RejectedExecutionException success) { + } catch (SecurityException ok) {} } - joinPool(se); } /** * schedule callable throws RejectedExecutionException if shutdown */ 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) { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + p.schedule(new NoOpCallable(), + MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (RejectedExecutionException success) { + } catch (SecurityException ok) {} } - 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) { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + p.scheduleAtFixedRate(new NoOpRunnable(), + MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (RejectedExecutionException success) { + } catch (SecurityException ok) {} } - joinPool(se); } /** * 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) { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.shutdown(); + p.scheduleWithFixedDelay(new NoOpRunnable(), + MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (RejectedExecutionException success) { + } catch (SecurityException ok) {} } - joinPool(se); } /** @@ -290,22 +306,19 @@ public class ScheduledExecutorTest exten * thread becomes active */ public void testGetActiveCount() throws InterruptedException { - final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); - final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try { + 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()); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getActiveCount()); - } finally { - done.countDown(); - joinPool(p); } } @@ -315,10 +328,10 @@ public class ScheduledExecutorTest exten */ public void testGetCompletedTaskCount() throws InterruptedException { final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch threadProceed = new CountDownLatch(1); - final CountDownLatch threadDone = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch threadProceed = new CountDownLatch(1); + final CountDownLatch threadDone = new CountDownLatch(1); assertEquals(0, p.getCompletedTaskCount()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -327,14 +340,16 @@ 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(); - delay(SHORT_DELAY_MS); - assertEquals(1, p.getCompletedTaskCount()); - } finally { - joinPool(p); + long startTime = System.nanoTime(); + while (p.getCompletedTaskCount() != 1) { + if (millisElapsedSince(startTime) > LONG_DELAY_MS) + fail("timed out"); + Thread.yield(); + } } } @@ -343,8 +358,9 @@ public class ScheduledExecutorTest exten */ public void testGetCorePoolSize() throws InterruptedException { ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - assertEquals(1, p.getCorePoolSize()); - joinPool(p); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getCorePoolSize()); + } } /** @@ -356,22 +372,19 @@ public class ScheduledExecutorTest exten final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS); final CountDownLatch threadsStarted = new CountDownLatch(THREADS); final CountDownLatch done = new CountDownLatch(1); - try { + 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(SMALL_DELAY_MS, MILLISECONDS)); - assertEquals(THREADS, p.getLargestPoolSize()); - } finally { - done.countDown(); - joinPool(p); + await(threadsStarted); assertEquals(THREADS, p.getLargestPoolSize()); } + assertEquals(THREADS, p.getLargestPoolSize()); } /** @@ -382,19 +395,16 @@ public class ScheduledExecutorTest exten final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try { + 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(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertEquals(1, p.getPoolSize()); - } finally { - done.countDown(); - joinPool(p); } } @@ -403,67 +413,80 @@ public class ScheduledExecutorTest exten * submitted */ public void testGetTaskCount() throws InterruptedException { - final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final CountDownLatch threadStarted = new CountDownLatch(1); + final int TASKS = 3; final CountDownLatch done = new CountDownLatch(1); - final int TASKS = 5; - try { + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p, done)) { + final CountDownLatch threadStarted = new CountDownLatch(1); assertEquals(0, p.getTaskCount()); - for (int i = 0; i < TASKS; i++) + 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(); - done.await(); + assertEquals(1 + TASKS, p.getTaskCount()); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); - assertEquals(TASKS, p.getTaskCount()); - } finally { - done.countDown(); - joinPool(p); + } + 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) {} } } /** - * isShutDown is false before shutdown, true after + * isShutdown is false before shutdown, true after */ public void testIsShutdown() { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try { assertFalse(p.isShutdown()); } @@ -473,30 +496,28 @@ public class ScheduledExecutorTest exten assertTrue(p.isShutdown()); } - /** * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final CountDownLatch threadStarted = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(1); - assertFalse(p.isTerminated()); - try { + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + assertFalse(p.isTerminated()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminated()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); - } finally { try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); } - assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); } /** @@ -506,49 +527,45 @@ public class ScheduledExecutorTest exten final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try { + try (PoolCleaner cleaner = cleaner(p)) { assertFalse(p.isTerminating()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); - done.await(); + await(done); }}); - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); - } finally { try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + assertFalse(p.isTerminating()); } - assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); - assertFalse(p.isTerminating()); } /** * getQueue returns the work queue, which contains queued tasks */ public void testGetQueue() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try { + 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(); - done.await(); + await(done); }}; tasks[i] = p.schedule(r, 1, MILLISECONDS); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); BlockingQueue q = p.getQueue(); assertTrue(q.contains(tasks[tasks.length - 1])); assertFalse(q.contains(tasks[0])); - } finally { - done.countDown(); - joinPool(p); } } @@ -556,20 +573,20 @@ public class ScheduledExecutorTest exten * remove(task) removes queued task, and fails to remove active task */ public void testRemove() throws InterruptedException { - final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - try { + 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(); - done.await(); + await(done); }}; tasks[i] = p.schedule(r, 1, MILLISECONDS); } - assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS)); + await(threadStarted); BlockingQueue q = p.getQueue(); assertFalse(p.remove((Runnable)tasks[0])); assertTrue(q.contains((Runnable)tasks[4])); @@ -580,9 +597,6 @@ public class ScheduledExecutorTest exten assertTrue(q.contains((Runnable)tasks[3])); assertTrue(p.remove((Runnable)tasks[3])); assertFalse(q.contains((Runnable)tasks[3])); - } finally { - done.countDown(); - joinPool(p); } } @@ -590,12 +604,15 @@ public class ScheduledExecutorTest exten * purge eventually removes cancelled tasks from the queue */ public void testPurge() throws InterruptedException { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for (int i = 0; i < tasks.length; i++) - tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), - LONG_DELAY_MS, MILLISECONDS); - try { + 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; @@ -607,160 +624,186 @@ public class ScheduledExecutorTest exten long count = p.getTaskCount(); if (count == max) return; - } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS); + } while (millisElapsedSince(startTime) < LONG_DELAY_MS); fail("Purge failed to remove cancelled tasks"); - } finally { - for (ScheduledFuture task : tasks) - task.cancel(true); - joinPool(p); } } /** - * 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); + 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 { - List l = p.shutdownNow(); - assertTrue(p.isShutdown()); - assertEquals(5, l.size()); + 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 { - 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)); + 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(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()); - ScheduledFuture task = - p.scheduleAtFixedRate(new NoOpRunnable(), 5, 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()); - BlockingQueue q = p.getQueue(); - assertTrue(p.getQueue().isEmpty()); - assertTrue(task.isDone()); - assertTrue(task.isCancelled()); - assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS)); - assertTrue(p.isTerminated()); - } - - /** - * 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 */ 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); } } @@ -768,13 +811,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); } } @@ -782,13 +823,11 @@ 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); } } @@ -796,13 +835,12 @@ public class ScheduledExecutorTest exten * invokeAny(null) throws NPE */ 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) {} } } @@ -810,13 +848,12 @@ public class ScheduledExecutorTest exten * invokeAny(empty collection) throws IAE */ 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) {} } } @@ -825,17 +862,16 @@ public class ScheduledExecutorTest exten */ 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); } } @@ -843,16 +879,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); + } } } @@ -860,15 +896,13 @@ public class ScheduledExecutorTest exten * invokeAny(c) returns result of some task */ public void testInvokeAny5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + 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); } } @@ -876,13 +910,12 @@ 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) {} } } @@ -890,12 +923,10 @@ public class ScheduledExecutorTest exten * invokeAll(empty collection) returns empty collection */ public void testInvokeAll2() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { List> r = e.invokeAll(new ArrayList>()); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -903,16 +934,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) {} } } @@ -920,18 +950,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); + } } } @@ -939,8 +969,8 @@ public class ScheduledExecutorTest exten * invokeAll(c) returns results of all completed tasks */ public void testInvokeAll5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); @@ -948,8 +978,6 @@ public class ScheduledExecutorTest exten assertEquals(2, futures.size()); for (Future future : futures) assertSame(TEST_STRING, future.get()); - } finally { - joinPool(e); } } @@ -957,13 +985,12 @@ 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, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -971,15 +998,14 @@ public class ScheduledExecutorTest exten * timed invokeAny(,,null) throws NPE */ 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, MEDIUM_DELAY_MS, null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -987,13 +1013,12 @@ public class ScheduledExecutorTest exten * timed invokeAny(empty collection) throws IAE */ 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); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } @@ -1002,17 +1027,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, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} latch.countDown(); - joinPool(e); } } @@ -1020,16 +1044,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); } } @@ -1037,15 +1063,15 @@ public class ScheduledExecutorTest exten * timed invokeAny(c) returns result of some task */ public void testTimedInvokeAny5() throws Exception { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { + 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); } } @@ -1053,13 +1079,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, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1067,15 +1092,14 @@ 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, MEDIUM_DELAY_MS, null); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1083,12 +1107,11 @@ public class ScheduledExecutorTest exten * timed invokeAll(empty collection) returns empty collection */ 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); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(new ArrayList>(), + MEDIUM_DELAY_MS, MILLISECONDS); assertTrue(r.isEmpty()); - } finally { - joinPool(e); } } @@ -1096,16 +1119,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, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } @@ -1113,19 +1135,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); + } } } @@ -1133,18 +1155,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 { + 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); } } @@ -1152,28 +1172,38 @@ 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"); + } + } } } - }