--- jsr166/src/test/tck/ScheduledExecutorTest.java 2003/09/08 12:12:42 1.3 +++ jsr166/src/test/tck/ScheduledExecutorTest.java 2015/10/05 21:54:33 1.66 @@ -1,557 +1,1203 @@ /* - * 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.*; - -public class ScheduledExecutorTest extends TestCase{ - - boolean flag = false; +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); } - private static long SHORT_DELAY_MS = 100; - private static long MEDIUM_DELAY_MS = 1000; - private static long LONG_DELAY_MS = 10000; - - static class MyRunnable implements Runnable { - volatile boolean waiting = true; - volatile boolean done = false; - public void run(){ - try{ - Thread.sleep(SHORT_DELAY_MS); - waiting = false; - done = true; - } catch(Exception e){ + /** + * execute successfully executes a runnable + */ + 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() 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() 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() 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() 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"); } } - static class MyCallable implements Callable { - volatile boolean waiting = true; - volatile boolean done = false; - public Object call(){ - try{ - Thread.sleep(SHORT_DELAY_MS); - waiting = false; - done = true; - }catch(Exception e){} - return Boolean.TRUE; + /** + * 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"); } } - public Runnable newRunnable(){ - return new Runnable(){ - public void run(){ - try{Thread.sleep(SHORT_DELAY_MS); - } catch(Exception e){ - } - } - }; + /** + * execute(null) throws NPE + */ + public void testExecuteNull() throws InterruptedException { + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.execute(null); + shouldThrow(); + } catch (NullPointerException success) {} + } } - public Runnable newNoopRunnable() { - return new Runnable(){ - public void run(){ - } - }; + /** + * schedule(null) throws NPE + */ + 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) {} + } } /** - * Test to verify execute successfully runs the given Runnable + * execute throws RejectedExecutionException if shutdown */ - public void testExecute(){ - try{ - MyRunnable runnable =new MyRunnable(); - ScheduledExecutor one = new ScheduledExecutor(1); - one.execute(runnable); - Thread.sleep(SHORT_DELAY_MS/2); - assertTrue(runnable.waiting); - one.shutdown(); - try{ - Thread.sleep(MEDIUM_DELAY_MS); - } catch(InterruptedException e){ - fail("unexpected exception"); - } - assertFalse(runnable.waiting); - assertTrue(runnable.done); - one.shutdown(); + 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) {} } - catch(Exception e){ - fail("unexpected exception"); + } + + /** + * schedule throws RejectedExecutionException if shutdown + */ + 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) {} } } /** - * Test to verify schedule successfully runs the given Callable. - * The waiting flag shows that the Callable is not started until - * immediately. + * schedule callable throws RejectedExecutionException if shutdown */ - public void testSchedule1(){ - try{ - MyCallable callable = new MyCallable(); - ScheduledExecutor one = new ScheduledExecutor(1); - Future f = one.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - assertTrue(callable.waiting); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(callable.done); - assertEquals(Boolean.TRUE, f.get()); - one.shutdown(); - }catch(RejectedExecutionException e){} - catch(Exception e){ - fail("unexpected exception"); + 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) {} } } /** - * Another version of schedule, only using Runnable instead of Callable + * scheduleAtFixedRate throws RejectedExecutionException if shutdown */ - public void testSchedule3(){ - try{ - MyRunnable runnable = new MyRunnable(); - ScheduledExecutor one = new ScheduledExecutor(1); - one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - Thread.sleep(SHORT_DELAY_MS/2); - assertTrue(runnable.waiting); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - one.shutdown(); - } catch(Exception e){ - fail("unexpected exception"); + 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) {} } } - + /** - * The final version of schedule, using both long, TimeUnit and Runnable + * scheduleWithFixedDelay throws RejectedExecutionException if shutdown */ - public void testSchedule4(){ - try{ - MyRunnable runnable = new MyRunnable(); - ScheduledExecutor one = new ScheduledExecutor(1); - one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - // Thread.sleep(505); - assertTrue(runnable.waiting); - Thread.sleep(MEDIUM_DELAY_MS); - assertTrue(runnable.done); - one.shutdown(); - } catch(Exception e){ - fail("unexpected exception"); + 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) {} } } - - - // exception tests /** - * Test to verify schedule(Runnable, long) throws RejectedExecutionException - * This occurs on an attempt to schedule a task on a shutdown executor + * getActiveCount increases but doesn't overestimate, when a + * thread becomes active */ - public void testSchedule1_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.schedule(new Runnable(){ - public void run(){} - }, 10000, TimeUnit.MILLISECONDS); - fail("shoud throw"); - }catch(RejectedExecutionException e){} + 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(MEDIUM_DELAY_MS, MILLISECONDS)); + assertEquals(1, p.getActiveCount()); + done.countDown(); + } } /** - * Test to verify schedule(Callable, long, TimeUnit) throws RejectedExecutionException - * This occurs on an attempt to schedule a task on a shutdown executor + * getCompletedTaskCount increases, but doesn't overestimate, + * when tasks complete */ - public void testSchedule2_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.schedule(new Callable(){ - public Object call(){ - return Boolean.TRUE; - } - }, (long)100, TimeUnit.SECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + 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(); + } + } } /** - * Test to verify schedule(Callable, long) throws RejectedExecutionException - * This occurs on an attempt to schedule a task on a shutdown executor + * getCorePoolSize returns size given in constructor if not otherwise set */ - public void testSchedule3_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.schedule(new Callable(){ - public Object call(){ - return Boolean.TRUE; - } - }, 10000, TimeUnit.MILLISECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + 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(MEDIUM_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(MEDIUM_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(1 + TASKS, p.getTaskCount()); + assertEquals(1 + TASKS, p.getCompletedTaskCount()); } /** - * Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws - * RejectedExecutionException. - * This occurs on an attempt to schedule a task on a shutdown executor + * getThreadFactory returns factory in constructor if not set */ - public void testScheduleAtFixedRate1_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.scheduleAtFixedRate(new Runnable(){ - public void run(){} - }, 100, 100, TimeUnit.SECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + 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()); + } } - + /** - * Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws - * RejectedExecutionException. - * This occurs on an attempt to schedule a task on a shutdown executor + * setThreadFactory sets the thread factory returned by getThreadFactory */ - public void testScheduleAtFixedRate2_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.scheduleAtFixedRate(new Runnable(){ - public void run(){} - }, 1, 100, TimeUnit.SECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + 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()); + } } /** - * Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws - * RejectedExecutionException. - * This occurs on an attempt to schedule a task on a shutdown executor + * setThreadFactory(null) throws NPE */ - public void testScheduleWithFixedDelay1_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.scheduleWithFixedDelay(new Runnable(){ - public void run(){} - }, 100, 100, TimeUnit.SECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + public void testSetThreadFactoryNull() throws InterruptedException { + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + try { + p.setThreadFactory(null); + shouldThrow(); + } catch (NullPointerException success) {} + } } /** - * Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws - * RejectedExecutionException. - * This occurs on an attempt to schedule a task on a shutdown executor + * isShutdown is false before shutdown, true after */ - public void testScheduleWithFixedDelay2_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.scheduleWithFixedDelay(new Runnable(){ - public void run(){} - }, 1, 100, TimeUnit.SECONDS); - fail("should throw"); - }catch(RejectedExecutionException e){} + public void testIsShutdown() { + + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try { + assertFalse(p.isShutdown()); + } + finally { + try { p.shutdown(); } catch (SecurityException ok) { return; } + } + assertTrue(p.isShutdown()); } /** - * Test to verify execute throws RejectedExecutionException - * This occurs on an attempt to schedule a task on a shutdown executor + * isTerminated is false before termination, true after */ - public void testExecute_RejectedExecutionException(){ - try{ - ScheduledExecutor se = new ScheduledExecutor(1); - se.shutdown(); - se.execute(new Runnable(){ - public void run(){} - }); - fail("should throw"); - }catch(RejectedExecutionException e){} + 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(MEDIUM_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()); + } + } + + /** + * 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(MEDIUM_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()); + } + } + + /** + * getQueue returns the work queue, which contains queued tasks + */ + public void testGetQueue() throws InterruptedException { + ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); + try (PoolCleaner cleaner = cleaner(p)) { + final CountDownLatch 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(MEDIUM_DELAY_MS, MILLISECONDS)); + BlockingQueue q = p.getQueue(); + assertTrue(q.contains(tasks[tasks.length - 1])); + assertFalse(q.contains(tasks[0])); + done.countDown(); + } + } + + /** + * remove(task) removes queued task, and fails to remove active task + */ + 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(MEDIUM_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(p.remove((Runnable)tasks[4])); + assertFalse(p.remove((Runnable)tasks[4])); + assertFalse(q.contains((Runnable)tasks[4])); + assertTrue(q.contains((Runnable)tasks[3])); + assertTrue(p.remove((Runnable)tasks[3])); + assertFalse(q.contains((Runnable)tasks[3])); + done.countDown(); + } } + /** + * purge eventually removes cancelled tasks from the queue + */ + 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()); + } /** - * Test to verify getActiveCount gives correct values - */ - public void testGetActiveCount(){ - ScheduledExecutor two = new ScheduledExecutor(2); + * 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 { - assertEquals(0, two.getActiveCount()); - two.execute(newRunnable()); - try{ - Thread.sleep(SHORT_DELAY_MS/2); - } catch(Exception e){ - fail("unexpected exception"); + 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()); + } + assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); + assertTrue(p.isTerminated()); + } + + /** + * 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()); } - assertEquals(1, two.getActiveCount()); - } finally { - two.shutdown(); + } + 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 { + 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); } } - + /** - * Test to verify getCompleteTaskCount gives correct values + * completed submit of runnable returns successfully */ - public void testGetCompletedTaskCount(){ - ScheduledExecutor two = new ScheduledExecutor(2); - try { - assertEquals(0, two.getCompletedTaskCount()); - two.execute(newRunnable()); - try{ - Thread.sleep(MEDIUM_DELAY_MS/2); - } catch(Exception e){ - fail("unexpected exception"); - } - assertEquals(1, two.getCompletedTaskCount()); - } finally { - two.shutdown(); + 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()); } } - + /** - * Test to verify getCorePoolSize gives correct values + * completed submit of (runnable, result) returns result */ - public void testGetCorePoolSize(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - assertEquals(1, one.getCorePoolSize()); - } finally { - one.shutdown(); + 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); } } - + /** - * Test to verify getLargestPoolSize gives correct values + * invokeAny(null) throws NPE */ - public void testGetLargestPoolSize(){ - ScheduledExecutor two = new ScheduledExecutor(2); - try { - assertEquals(0, two.getLargestPoolSize()); - two.execute(newRunnable()); - two.execute(newRunnable()); - try{ - Thread.sleep(SHORT_DELAY_MS/2); - } catch(Exception e){ - fail("unexpected exception"); + public void testInvokeAny1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAny(null); + shouldThrow(); + } catch (NullPointerException success) {} + } + } + + /** + * invokeAny(empty collection) throws IAE + */ + 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) {} + } + } + + /** + * invokeAny(c) throws NPE if c has null elements + */ + public void testInvokeAny3() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + List> l = new ArrayList>(); + l.add(latchAwaitingStringTask(latch)); + l.add(null); + try { + e.invokeAny(l); + shouldThrow(); + } catch (NullPointerException success) {} + latch.countDown(); + } + } + + /** + * invokeAny(c) throws ExecutionException if no task completes + */ + 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); } - assertEquals(2, two.getLargestPoolSize()); - } finally { - two.shutdown(); } } - + /** - * Test to verify getPoolSize gives correct values + * invokeAny(c) returns result of some task */ - public void testGetPoolSize(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - assertEquals(0, one.getPoolSize()); - one.execute(newRunnable()); - assertEquals(1, one.getPoolSize()); - } finally { - one.shutdown(); + 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); } } - + /** - * Test to verify getTaskCount gives correct values + * invokeAll(null) throws NPE */ - public void testGetTaskCount(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - assertEquals(0, one.getTaskCount()); - for(int i = 0; i < 5; i++) - one.execute(newRunnable()); - try{ - Thread.sleep(SHORT_DELAY_MS/2); - } catch(Exception e){ - fail("unexpected exception"); - } - assertEquals(5, one.getTaskCount()); - } finally { - one.shutdown(); - } - } - - /** - * Test to verify isShutDown gives correct values - */ - public void testIsShutdown(){ - - ScheduledExecutor one = new ScheduledExecutor(1); - try { - assertFalse(one.isShutdown()); + public void testInvokeAll1() throws Exception { + final ExecutorService e = new ScheduledThreadPoolExecutor(2); + try (PoolCleaner cleaner = cleaner(e)) { + try { + e.invokeAll(null); + shouldThrow(); + } catch (NullPointerException success) {} } - finally { - one.shutdown(); + } + + /** + * 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()); } - assertTrue(one.isShutdown()); } - /** - * Test to verify isTerminated gives correct values - * Makes sure termination does not take an innapropriate - * amount of time + * invokeAll(c) throws NPE if c has null elements */ - public void testIsTerminated(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - one.execute(newRunnable()); - } finally { - one.shutdown(); - } - boolean flag = false; - try{ - flag = one.awaitTermination(10, TimeUnit.SECONDS); - } catch(Exception e){ - fail("unexpected exception"); - } - assertTrue(one.isTerminated()); - if(!flag) - fail("ThreadPoolExecutor - thread pool did not terminate within suitable timeframe"); + 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) {} + } } /** - * Test to verify that purge correctly removes cancelled tasks - * from the queue + * get of invokeAll(c) throws exception on failed task */ - public void testPurge(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - ScheduledCancellable[] tasks = new ScheduledCancellable[5]; - for(int i = 0; i < 5; i++){ - tasks[i] = one.schedule(newRunnable(), 1, TimeUnit.MILLISECONDS); + 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); } - int max = 5; - if (tasks[4].cancel(true)) --max; - if (tasks[3].cancel(true)) --max; - one.purge(); - long count = one.getTaskCount(); - assertTrue(count > 0 && count <= max); - } finally { - one.shutdown(); } } /** - * Test to verify shutDownNow returns a list - * containing the correct number of elements + * invokeAll(c) returns results of all completed tasks */ - public void testShutDownNow(){ - ScheduledExecutor one = new ScheduledExecutor(1); - for(int i = 0; i < 5; i++) - one.schedule(newRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - List l = one.shutdownNow(); - assertTrue(one.isShutdown()); - assertTrue(l.size() > 0 && l.size() <= 5); + 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()); + } } - public void testShutDown1(){ - try { - ScheduledExecutor one = new ScheduledExecutor(1); - assertTrue(one.getExecuteExistingDelayedTasksAfterShutdownPolicy()); - assertFalse(one.getContinueExistingPeriodicTasksAfterShutdownPolicy()); + /** + * 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) {} + } + } - ScheduledCancellable[] tasks = new ScheduledCancellable[5]; - for(int i = 0; i < 5; i++) - tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS); - one.shutdown(); - BlockingQueue q = one.getQueue(); - for (Iterator it = q.iterator(); it.hasNext();) { - ScheduledCancellable t = (ScheduledCancellable)it.next(); - assertFalse(t.isCancelled()); - } - assertTrue(one.isShutdown()); - Thread.sleep(SHORT_DELAY_MS); - for (int i = 0; i < 5; ++i) { - assertTrue(tasks[i].isDone()); - assertFalse(tasks[i].isCancelled()); - } - + /** + * timed invokeAny(,,null) throws NPE + */ + 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) {} } - catch(Exception ex) { - fail("unexpected exception"); + } + + /** + * timed invokeAny(empty collection) throws IAE + */ + 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) {} } } + /** + * timed invokeAny(c) throws NPE if c has null elements + */ + 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); + try { + e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} + latch.countDown(); + } + } - public void testShutDown2(){ - try { - ScheduledExecutor one = new ScheduledExecutor(1); - one.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - ScheduledCancellable[] tasks = new ScheduledCancellable[5]; - for(int i = 0; i < 5; i++) - tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS); - one.shutdown(); - assertTrue(one.isShutdown()); - BlockingQueue q = one.getQueue(); - assertTrue(q.isEmpty()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(one.isTerminated()); + /** + * timed invokeAny(c) throws ExecutionException if no task completes + */ + public void testTimedInvokeAny4() 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, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (ExecutionException success) { + assertTrue(success.getCause() instanceof NullPointerException); + } } - catch(Exception ex) { - fail("unexpected exception"); + } + + /** + * timed invokeAny(c) returns result of some task + */ + 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, MEDIUM_DELAY_MS, MILLISECONDS); + assertSame(TEST_STRING, result); } } + /** + * timed invokeAll(null) throws NPE + */ + 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) {} + } + } - public void testShutDown3(){ - try { - ScheduledExecutor one = new ScheduledExecutor(1); - one.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - ScheduledCancellable task = - one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS); - one.shutdown(); - assertTrue(one.isShutdown()); - BlockingQueue q = one.getQueue(); - assertTrue(q.isEmpty()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(one.isTerminated()); + /** + * timed invokeAll(,,null) throws NPE + */ + 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) {} } - catch(Exception ex) { - fail("unexpected exception"); + } + + /** + * 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()); } } - public void testShutDown4(){ - ScheduledExecutor one = new ScheduledExecutor(1); - try { - one.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); - ScheduledCancellable task = - one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS); - assertFalse(task.isCancelled()); - one.shutdown(); - assertFalse(task.isCancelled()); - assertFalse(one.isTerminated()); - assertTrue(one.isShutdown()); - Thread.sleep(SHORT_DELAY_MS); - assertFalse(task.isCancelled()); - task.cancel(true); - assertTrue(task.isCancelled()); - Thread.sleep(SHORT_DELAY_MS); - assertTrue(one.isTerminated()); + /** + * timed invokeAll(c) throws NPE if c has null elements + */ + 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); + try { + e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); + shouldThrow(); + } catch (NullPointerException success) {} } - catch(Exception ex) { - fail("unexpected exception"); + } + + /** + * get of element of invokeAll(c) throws exception on failed task + */ + 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> 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 { - one.shutdownNow(); + } + + /** + * timed invokeAll(c) returns results of all completed tasks + */ + 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> 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"); + } + } } }