--- jsr166/src/test/tck/ScheduledExecutorTest.java 2003/12/22 00:48:56 1.10 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2015/10/05 22:09:02 1.67 @@ -1,847 +1,1204 @@ /* - * Written by members of JCP JSR-166 Expert Group and released to the - * public domain. Use, modify, and redistribute this code in any way - * without acknowledgement. Other contributors include Andrew Wright, - * Jeffrey Hayes, Pat Fischer, Mike Judd. + * 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/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 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); + return new TestSuite(ScheduledExecutorTest.class); } - /** * execute successfully executes a runnable */ - public void testExecute() { - try { - TrackedShortRunnable runnable =new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.execute(runnable); - assertFalse(runnable.done); - Thread.sleep(SHORT_DELAY_MS); - p1.shutdown(); - try { - Thread.sleep(MEDIUM_DELAY_MS); - } catch(InterruptedException e){ - unexpectedException(); - } - assertTrue(runnable.done); - p1.shutdown(); - joinPool(p1); - } - catch(Exception e){ - unexpectedException(); + public void testExecute() throws InterruptedException { + 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)); } - } - /** * delayed schedule of callable successfully executes after delay */ - public void testSchedule1() { - try { - TrackedCallable callable = new TrackedCallable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - assertFalse(callable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(callable.done); - assertEquals(Boolean.TRUE, f.get()); - p1.shutdown(); - joinPool(p1); - } catch(RejectedExecutionException e){} - catch(Exception e){ - e.printStackTrace(); - unexpectedException(); + public void testSchedule1() throws Exception { + 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()); + assertTrue(done.await(0L, MILLISECONDS)); } } /** - * delayed schedule of runnable successfully executes after delay - */ - public void testSchedule3() { - try { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.schedule(runnable, SMALL_DELAY_MS, TimeUnit.MILLISECONDS); - Thread.sleep(SHORT_DELAY_MS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - p1.shutdown(); - joinPool(p1); - } catch(Exception e){ - unexpectedException(); + * delayed schedule of runnable successfully executes after delay + */ + public void testSchedule3() throws Exception { + 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() { - try { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - h.cancel(true); - p1.shutdown(); - joinPool(p1); - } catch(Exception e){ - unexpectedException(); + public void testSchedule4() throws Exception { + 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() { - try { - TrackedShortRunnable runnable = new TrackedShortRunnable(); - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - assertFalse(runnable.done); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - h.cancel(true); - p1.shutdown(); - joinPool(p1); - } catch(Exception e){ - unexpectedException(); + public void testSchedule5() throws Exception { + 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); + } + } + + static class RunnableCounter implements Runnable { + AtomicInteger count = new AtomicInteger(0); + public void run() { count.getAndIncrement(); } + } + + /** + * scheduleAtFixedRate executes series of tasks at given rate + */ + public void testFixedRateSequence() throws InterruptedException { + 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); + done.await(); + 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); + 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); + done.await(); + 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 + * execute(null) throws NPE */ - public void testExecuteNull() { - ScheduledThreadPoolExecutor se = null; - try { - se = new ScheduledThreadPoolExecutor(1); - se.execute(null); - shouldThrow(); - } catch(NullPointerException success){} - catch(Exception e){ - unexpectedException(); + public void testExecuteNull() throws InterruptedException { + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.execute(null); + shouldThrow(); + } catch (NullPointerException success) {} } - - joinPool(se); } /** - * schedule (null) throws NPE + * schedule(null) throws NPE */ - public void testScheduleNull() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - TrackedCallable callable = null; - Future f = se.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(NullPointerException success){} - catch(Exception e){ - unexpectedException(); + public void testScheduleNull() throws InterruptedException { + 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) {} } - joinPool(se); } - + /** * execute throws RejectedExecutionException if shutdown */ - public void testSchedule1_RejectedExecutionException() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpRunnable(), - MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(RejectedExecutionException success){ + public void testSchedule1_RejectedExecutionException() throws InterruptedException { + 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() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(RejectedExecutionException success){ + public void testSchedule2_RejectedExecutionException() throws InterruptedException { + 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() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.schedule(new NoOpCallable(), - MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(RejectedExecutionException success){ - } - joinPool(se); + public void testSchedule3_RejectedExecutionException() throws InterruptedException { + 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) {} + } } /** - * scheduleAtFixedRate throws RejectedExecutionException if shutdown - */ - public void testScheduleAtFixedRate1_RejectedExecutionException() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.scheduleAtFixedRate(new NoOpRunnable(), - MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(RejectedExecutionException success){ - } - joinPool(se); + * scheduleAtFixedRate throws RejectedExecutionException if shutdown + */ + public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException { + 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) {} + } } - + /** * scheduleWithFixedDelay throws RejectedExecutionException if shutdown */ - public void testScheduleWithFixedDelay1_RejectedExecutionException() { - ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1); - try { - se.shutdown(); - se.scheduleWithFixedDelay(new NoOpRunnable(), - MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); - shouldThrow(); - } catch(RejectedExecutionException success){ - } - joinPool(se); + public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException { + 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) {} + } } /** - * getActiveCount increases but doesn't overestimate, when a - * thread becomes active - */ - public void testGetActiveCount() { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getActiveCount()); - p2.execute(new SmallRunnable()); - try { - Thread.sleep(SHORT_DELAY_MS); - } catch(Exception e){ - unexpectedException(); - } - assertEquals(1, p2.getActiveCount()); - joinPool(p2); - } - - /** - * getCompletedTaskCount increases, but doesn't overestimate, - * when tasks complete - */ - public void testGetCompletedTaskCount() { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getCompletedTaskCount()); - p2.execute(new SmallRunnable()); - try { - Thread.sleep(MEDIUM_DELAY_MS); - } catch(Exception e){ - unexpectedException(); + * getActiveCount increases but doesn't overestimate, when a + * thread becomes active + */ + public void testGetActiveCount() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + assertEquals(0, p.getActiveCount()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getActiveCount()); + done.await(); + }}); + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(1, p.getActiveCount()); + done.countDown(); } - assertEquals(1, p2.getCompletedTaskCount()); - joinPool(p2); } - + /** - * getCorePoolSize returns size given in constructor if not otherwise set - */ - public void testGetCorePoolSize() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(1, p1.getCorePoolSize()); - joinPool(p1); + * getCompletedTaskCount increases, but doesn't overestimate, + * when tasks complete + */ + public void testGetCompletedTaskCount() throws InterruptedException { + 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()); + threadProceed.await(); + threadDone.countDown(); + }}); + await(threadStarted); + assertEquals(0, p.getCompletedTaskCount()); + threadProceed.countDown(); + threadDone.await(); + long startTime = System.nanoTime(); + while (p.getCompletedTaskCount() != 1) { + if (millisElapsedSince(startTime) > LONG_DELAY_MS) + fail("timed out"); + Thread.yield(); + } + } } - + /** - * getLargestPoolSize increases, but doesn't overestimate, when - * multiple threads active + * getCorePoolSize returns size given in constructor if not otherwise set */ - public void testGetLargestPoolSize() { - ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2); - assertEquals(0, p2.getLargestPoolSize()); - p2.execute(new SmallRunnable()); - p2.execute(new SmallRunnable()); - try { - Thread.sleep(SHORT_DELAY_MS); - } catch(Exception e){ - unexpectedException(); - } - assertEquals(2, p2.getLargestPoolSize()); - joinPool(p2); - } - - /** - * getPoolSize increases, but doesn't overestimate, when threads - * become active - */ - public void testGetPoolSize() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(0, p1.getPoolSize()); - p1.execute(new SmallRunnable()); - assertEquals(1, p1.getPoolSize()); - joinPool(p1); - } - - /** - * getTaskCount increases, but doesn't overestimate, when tasks - * submitted - */ - public void testGetTaskCount() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertEquals(0, p1.getTaskCount()); - for(int i = 0; i < 5; i++) - p1.execute(new SmallRunnable()); - try { - Thread.sleep(SHORT_DELAY_MS); - } catch(Exception e){ - unexpectedException(); + public void testGetCorePoolSize() throws InterruptedException { + ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(1, p.getCorePoolSize()); + } + } + + /** + * getLargestPoolSize increases, but doesn't overestimate, when + * multiple threads active + */ + public void testGetLargestPoolSize() throws InterruptedException { + 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)) { + assertEquals(0, p.getLargestPoolSize()); + for (int i = 0; i < THREADS; i++) + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadsStarted.countDown(); + done.await(); + assertEquals(THREADS, p.getLargestPoolSize()); + }}); + assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(THREADS, p.getLargestPoolSize()); + done.countDown(); + } + assertEquals(THREADS, p.getLargestPoolSize()); + } + + /** + * getPoolSize increases, but doesn't overestimate, when threads + * become active + */ + public void testGetPoolSize() throws InterruptedException { + final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + try (PoolCleaner cleaner = cleaner(p)) { + assertEquals(0, p.getPoolSize()); + p.execute(new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + assertEquals(1, p.getPoolSize()); + done.await(); + }}); + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(1, p.getPoolSize()); + done.countDown(); + } + } + + /** + * getTaskCount increases, but doesn't overestimate, when tasks + * submitted + */ + public void testGetTaskCount() throws InterruptedException { + 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(); + done.await(); + }}); + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + 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()); + done.await(); + }}); + } + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(0, p.getCompletedTaskCount()); } - assertEquals(5, p1.getTaskCount()); - joinPool(p1); + assertEquals(1 + TASKS, p.getTaskCount()); + assertEquals(1 + TASKS, p.getCompletedTaskCount()); } - /** + /** * getThreadFactory returns factory in constructor if not set */ - public void testGetThreadFactory() { - ThreadFactory tf = new SimpleThreadFactory(); - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf); - assertSame(tf, p.getThreadFactory()); - p.shutdown(); - joinPool(p); + public void testGetThreadFactory() throws InterruptedException { + 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() { - ThreadFactory tf = new SimpleThreadFactory(); - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - p.setThreadFactory(tf); - assertSame(tf, p.getThreadFactory()); - p.shutdown(); - joinPool(p); + public void testSetThreadFactory() throws InterruptedException { + ThreadFactory threadFactory = new SimpleThreadFactory(); + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + p.setThreadFactory(threadFactory); + assertSame(threadFactory, p.getThreadFactory()); + } } - /** + /** * setThreadFactory(null) throws NPE */ - public void testSetThreadFactoryNull() { - ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); - try { - p.setThreadFactory(null); - shouldThrow(); - } catch (NullPointerException success) { - } finally { - joinPool(p); + public void testSetThreadFactoryNull() throws InterruptedException { + 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 + * isShutdown is false before shutdown, true after */ public void testIsShutdown() { - - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); + + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try { - assertFalse(p1.isShutdown()); + assertFalse(p.isShutdown()); } finally { - p1.shutdown(); + try { p.shutdown(); } catch (SecurityException ok) { return; } } - assertTrue(p1.isShutdown()); + assertTrue(p.isShutdown()); } - /** - * isTerminated is false before termination, true after + * isTerminated is false before termination, true after */ - public void testIsTerminated() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - try { - p1.execute(new SmallRunnable()); - } finally { - p1.shutdown(); + public void testIsTerminated() throws InterruptedException { + 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(); + done.await(); + }}); + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertFalse(p.isTerminating()); + done.countDown(); + try { p.shutdown(); } catch (SecurityException ok) { return; } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); } - try { - assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS)); - assertTrue(p1.isTerminated()); - } catch(Exception e){ - unexpectedException(); - } } /** - * isTerminating is not true when running or when terminated - */ - public void testIsTerminating() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - assertFalse(p1.isTerminating()); - try { - p1.execute(new SmallRunnable()); - assertFalse(p1.isTerminating()); - } finally { - p1.shutdown(); + * isTerminating is not true when running or when terminated + */ + public void testIsTerminating() throws InterruptedException { + 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(); + done.await(); + }}); + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + 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()); } - try { - assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS)); - assertTrue(p1.isTerminated()); - assertFalse(p1.isTerminating()); - } catch(Exception e){ - unexpectedException(); - } } /** * getQueue returns the work queue, which contains queued tasks */ - public void testGetQueue() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for(int i = 0; i < 5; i++){ - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS); - } - try { - Thread.sleep(SHORT_DELAY_MS); - BlockingQueue q = p1.getQueue(); - assertTrue(q.contains(tasks[4])); + public void testGetQueue() throws InterruptedException { + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + ScheduledFuture[] tasks = new ScheduledFuture[5]; + for (int i = 0; i < tasks.length; i++) { + Runnable r = new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + done.await(); + }}; + tasks[i] = p.schedule(r, 1, MILLISECONDS); + } + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + BlockingQueue q = p.getQueue(); + assertTrue(q.contains(tasks[tasks.length - 1])); assertFalse(q.contains(tasks[0])); - p1.shutdownNow(); - } catch(Exception e) { - unexpectedException(); - } finally { - joinPool(p1); + done.countDown(); } } /** * remove(task) removes queued task, and fails to remove active task */ - public void testRemove() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for(int i = 0; i < 5; i++){ - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS); - } - try { - Thread.sleep(SHORT_DELAY_MS); - BlockingQueue q = p1.getQueue(); - assertFalse(p1.remove((Runnable)tasks[0])); + public void testRemove() throws InterruptedException { + final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + ScheduledFuture[] tasks = new ScheduledFuture[5]; + final CountDownLatch threadStarted = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(1); + for (int i = 0; i < tasks.length; i++) { + Runnable r = new CheckedRunnable() { + public void realRun() throws InterruptedException { + threadStarted.countDown(); + done.await(); + }}; + tasks[i] = p.schedule(r, 1, MILLISECONDS); + } + assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS)); + 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])); - p1.shutdownNow(); - } catch(Exception e) { - unexpectedException(); - } finally { - joinPool(p1); + done.countDown(); } } /** - * purge removes cancelled tasks from the queue + * purge eventually removes cancelled tasks from the queue */ - public void testPurge() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - ScheduledFuture[] tasks = new ScheduledFuture[5]; - for(int i = 0; i < 5; i++){ - tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS); + public void testPurge() throws InterruptedException { + 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.) + 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, + * 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); + assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS)); + assertEquals(poolSize, p.getActiveCount()); + assertEquals(0, p.getCompletedTaskCount()); + final List queuedTasks; + try { + queuedTasks = p.shutdownNow(); + } catch (SecurityException ok) { + 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()); + } + + /** + * shutdownNow returns a list containing tasks that were not run, + * and those tasks are drained from the queue + */ + public void testShutdownNow_delayedTasks() throws InterruptedException { + 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.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()); } - int max = 5; - if (tasks[4].cancel(true)) --max; - if (tasks[3].cancel(true)) --max; - p1.purge(); - long count = p1.getTaskCount(); - assertTrue(count > 0 && count <= max); - joinPool(p1); + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); } /** - * shutDownNow returns a list containing tasks that were not run + * 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()); + 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()); + } + } + 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 testShutDownNow() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - for(int i = 0; i < 5; i++) - p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - List l = p1.shutdownNow(); - assertTrue(p1.isShutdown()); - assertTrue(l.size() > 0 && l.size() <= 5); - joinPool(p1); + public void testSubmitCallable() throws Exception { + 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); + } } /** - * In default setting, shutdown cancels periodic but not delayed - * tasks at shutdown + * completed submit of runnable returns successfully */ - public void testShutDown1() { - try { - 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, TimeUnit.MILLISECONDS); - p1.shutdown(); - BlockingQueue q = p1.getQueue(); - for (Iterator it = q.iterator(); it.hasNext();) { - ScheduledFuture t = (ScheduledFuture)it.next(); - assertFalse(t.isCancelled()); - } - assertTrue(p1.isShutdown()); - Thread.sleep(SMALL_DELAY_MS); - for (int i = 0; i < 5; ++i) { - assertTrue(tasks[i].isDone()); - assertFalse(tasks[i].isCancelled()); - } - - } - catch(Exception ex) { - unexpectedException(); + public void testSubmitRunnable() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + Future future = e.submit(new NoOpRunnable()); + future.get(); + assertTrue(future.isDone()); } } - /** - * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false, - * delayed tasks are cancelled at shutdown + * completed submit of (runnable, result) returns result */ - public void testShutDown2() { - try { - 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, TimeUnit.MILLISECONDS); - p1.shutdown(); - assertTrue(p1.isShutdown()); - BlockingQueue q = p1.getQueue(); - assertTrue(q.isEmpty()); - Thread.sleep(SMALL_DELAY_MS); - assertTrue(p1.isTerminated()); - } - catch(Exception ex) { - unexpectedException(); + public void testSubmitRunnable2() throws Exception { + 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); } } - /** - * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false, - * periodic tasks are not cancelled at shutdown + * invokeAny(null) throws NPE */ - public void testShutDown3() { - try { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - ScheduledFuture task = - p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS); - p1.shutdown(); - assertTrue(p1.isShutdown()); - BlockingQueue q = p1.getQueue(); - assertTrue(q.isEmpty()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(p1.isTerminated()); - } - catch(Exception ex) { - unexpectedException(); + public void testInvokeAny1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true, - * periodic tasks are cancelled at shutdown + * invokeAny(empty collection) throws IAE */ - public void testShutDown4() { - ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); - try { - p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); - ScheduledFuture task = - p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS); - assertFalse(task.isCancelled()); - p1.shutdown(); - assertFalse(task.isCancelled()); - assertFalse(p1.isTerminated()); - assertTrue(p1.isShutdown()); - Thread.sleep(SHORT_DELAY_MS); - assertFalse(task.isCancelled()); - task.cancel(true); - assertTrue(task.isCancelled()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(p1.isTerminated()); - } - catch(Exception ex) { - unexpectedException(); - } - finally { - p1.shutdownNow(); + public void testInvokeAny2() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>()); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } /** - * completed submit of callable returns result + * invokeAny(c) throws NPE if c has null elements */ - public void testSubmitCallable() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - Future future = e.submit(new StringTask()); - String result = future.get(); - assertSame(TEST_STRING, result); - } - catch (ExecutionException ex) { - unexpectedException(); - } - catch (InterruptedException ex) { - unexpectedException(); - } finally { - joinPool(e); + public void testInvokeAny3() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); + try { + e.invokeAny(l); + shouldThrow(); + } catch (NullPointerException success) {} + latch.countDown(); } } /** - * completed submit of runnable returns successfully + * invokeAny(c) throws ExecutionException if no task completes */ - public void testSubmitRunnable() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - Future future = e.submit(new NoOpRunnable()); - future.get(); - assertTrue(future.isDone()); - } - catch (ExecutionException ex) { - unexpectedException(); - } - catch (InterruptedException ex) { - unexpectedException(); - } finally { - joinPool(e); + public void testInvokeAny4() throws Exception { + 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); + } } } /** - * completed submit of (runnable, result) returns result + * invokeAny(c) returns result of some task */ - public void testSubmitRunnable2() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - Future future = e.submit(new NoOpRunnable(), TEST_STRING); - String result = future.get(); + public void testInvokeAny5() throws Exception { + 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); } - catch (ExecutionException ex) { - unexpectedException(); + } + + /** + * invokeAll(null) throws NPE + */ + public void testInvokeAll1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null); + shouldThrow(); + } catch (NullPointerException success) {} } - catch (InterruptedException ex) { - unexpectedException(); - } finally { - joinPool(e); + } + + /** + * invokeAll(empty collection) returns empty collection + */ + public void testInvokeAll2() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(new ArrayList>()); + assertTrue(r.isEmpty()); } } + /** + * invokeAll(c) throws NPE if c has null elements + */ + public void testInvokeAll3() throws Exception { + 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) {} + } + } + /** + * get of invokeAll(c) throws exception on failed task + */ + public void testInvokeAll4() throws Exception { + 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); + } + } + } + /** + * invokeAll(c) returns results of all completed tasks + */ + public void testInvokeAll5() throws Exception { + 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()); + } + } + /** + * timed invokeAny(null) throws NPE + */ + public void testTimedInvokeAny1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} + } + } /** - * invokeAny(null) throws NPE + * timed invokeAny(,,null) throws NPE */ - public void testInvokeAny1() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(null); - } catch (NullPointerException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + public void testTimedInvokeAnyNullTimeUnit() throws Exception { + 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) {} } } /** - * invokeAny(empty collection) throws IAE + * timed invokeAny(empty collection) throws IAE */ - public void testInvokeAny2() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAny(new ArrayList>()); - } catch (IllegalArgumentException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + public void testTimedInvokeAny2() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(new ArrayList>(), MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (IllegalArgumentException success) {} } } /** - * invokeAny(c) throws NPE if c has null elements + * timed invokeAny(c) throws NPE if c has null elements */ - public void testInvokeAny3() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); - l.add(new StringTask()); + public void testTimedInvokeAny3() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); l.add(null); - e.invokeAny(l); - } catch (NullPointerException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} + latch.countDown(); } } /** - * invokeAny(c) throws ExecutionException if no task completes + * timed invokeAny(c) throws ExecutionException if no task completes */ - public void testInvokeAny4() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); + public void testTimedInvokeAny4() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); l.add(new NPETask()); - e.invokeAny(l); - } catch (ExecutionException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } } /** - * invokeAny(c) returns result of some task + * timed invokeAny(c) returns result of some task */ - public void testInvokeAny5() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); + public void testTimedInvokeAny5() throws Exception { + 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); + String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); assertSame(TEST_STRING, result); - } catch (ExecutionException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); } } /** - * invokeAll(null) throws NPE + * timed invokeAll(null) throws NPE */ - public void testInvokeAll1() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - e.invokeAll(null); - } catch (NullPointerException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + public void testTimedInvokeAll1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * invokeAll(empty collection) returns empty collection + * timed invokeAll(,,null) throws NPE */ - public void testInvokeAll2() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - List> r = e.invokeAll(new ArrayList>()); + public void testTimedInvokeAllNullTimeUnit() throws Exception { + 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) {} + } + } + + /** + * timed invokeAll(empty collection) returns empty collection + */ + public void testTimedInvokeAll2() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> r = e.invokeAll(new ArrayList>(), + MEDIUM_DELAY_MS, MILLISECONDS); assertTrue(r.isEmpty()); - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); } } /** - * invokeAll(c) throws NPE if c has null elements + * timed invokeAll(c) throws NPE if c has null elements */ - public void testInvokeAll3() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); + public void testTimedInvokeAll3() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); l.add(new StringTask()); l.add(null); - e.invokeAll(l); - } catch (NullPointerException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + try { + e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } } /** - * get of invokeAll(c) throws exception on failed task + * get of element of invokeAll(c) throws exception on failed task */ - public void testInvokeAll4() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); + public void testTimedInvokeAll4() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); l.add(new NPETask()); - List> result = e.invokeAll(l); - assertEquals(1, result.size()); - for (Iterator> it = result.iterator(); it.hasNext();) - it.next().get(); - } catch(ExecutionException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + 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); + } } } /** - * invokeAll(c) returns results of all completed tasks + * timed invokeAll(c) returns results of all completed tasks */ - public void testInvokeAll5() { - ExecutorService e = new ScheduledThreadPoolExecutor(2); - try { - ArrayList> l = new ArrayList>(); + public void testTimedInvokeAll5() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); l.add(new StringTask()); l.add(new StringTask()); - List> result = e.invokeAll(l); - assertEquals(2, result.size()); - for (Iterator> it = result.iterator(); it.hasNext();) - assertSame(TEST_STRING, it.next().get()); - } catch (ExecutionException success) { - } catch(Exception ex) { - unexpectedException(); - } finally { - joinPool(e); + List> futures = + e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); + assertEquals(2, futures.size()); + for (Future future : futures) + assertSame(TEST_STRING, future.get()); } } + /** + * timed invokeAll(c) cancels tasks not completed by timeout + */ + public void testTimedInvokeAll6() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + for (long timeout = timeoutMillis();;) { + List> tasks = new ArrayList<>(); + tasks.add(new StringTask("0")); + tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING)); + tasks.add(new StringTask("2")); + long startTime = System.nanoTime(); + List> futures = + e.invokeAll(tasks, timeout, MILLISECONDS); + assertEquals(tasks.size(), futures.size()); + assertTrue(millisElapsedSince(startTime) >= timeout); + for (Future future : futures) + assertTrue(future.isDone()); + assertTrue(futures.get(1).isCancelled()); + try { + assertEquals("0", futures.get(0).get()); + assertEquals("2", futures.get(2).get()); + break; + } catch (CancellationException retryWithLongerTimeout) { + timeout *= 2; + if (timeout >= LONG_DELAY_MS / 2) + fail("expected exactly one task to be cancelled"); + } + } + } + } }