ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorSubclassTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ScheduledExecutorSubclassTest.java (file contents):
Revision 1.59 by jsr166, Sun Oct 25 02:58:25 2015 UTC vs.
Revision 1.70 by jsr166, Mon Jan 8 02:04:15 2018 UTC

# Line 5 | Line 5
5   */
6  
7   import static java.util.concurrent.TimeUnit.MILLISECONDS;
8 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
9   import static java.util.concurrent.TimeUnit.SECONDS;
10  
11   import java.util.ArrayList;
12 + import java.util.Collection;
13 + import java.util.Collections;
14   import java.util.HashSet;
15   import java.util.List;
16   import java.util.concurrent.BlockingQueue;
# Line 16 | Line 19 | import java.util.concurrent.Cancellation
19   import java.util.concurrent.CountDownLatch;
20   import java.util.concurrent.Delayed;
21   import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Executors;
22   import java.util.concurrent.ExecutorService;
23   import java.util.concurrent.Future;
24   import java.util.concurrent.RejectedExecutionException;
# Line 25 | Line 27 | import java.util.concurrent.RunnableSche
27   import java.util.concurrent.ScheduledFuture;
28   import java.util.concurrent.ScheduledThreadPoolExecutor;
29   import java.util.concurrent.ThreadFactory;
30 + import java.util.concurrent.ThreadLocalRandom;
31   import java.util.concurrent.ThreadPoolExecutor;
32   import java.util.concurrent.TimeoutException;
33   import java.util.concurrent.TimeUnit;
34 + import java.util.concurrent.atomic.AtomicBoolean;
35   import java.util.concurrent.atomic.AtomicInteger;
36 + import java.util.concurrent.atomic.AtomicLong;
37 + import java.util.stream.Stream;
38  
39   import junit.framework.Test;
40   import junit.framework.TestSuite;
# Line 42 | Line 48 | public class ScheduledExecutorSubclassTe
48      }
49  
50      static class CustomTask<V> implements RunnableScheduledFuture<V> {
51 <        RunnableScheduledFuture<V> task;
51 >        private final RunnableScheduledFuture<V> task;
52          volatile boolean ran;
53 <        CustomTask(RunnableScheduledFuture<V> t) { task = t; }
53 >        CustomTask(RunnableScheduledFuture<V> task) { this.task = task; }
54          public boolean isPeriodic() { return task.isPeriodic(); }
55          public void run() {
56              ran = true;
# Line 199 | Line 205 | public class ScheduledExecutorSubclassTe
205      }
206  
207      /**
208 <     * scheduleAtFixedRate executes series of tasks at given rate
208 >     * scheduleAtFixedRate executes series of tasks at given rate.
209 >     * Eventually, it must hold that:
210 >     *   cycles - 1 <= elapsedMillis/delay < cycles
211       */
212      public void testFixedRateSequence() throws InterruptedException {
213          final CustomExecutor p = new CustomExecutor(1);
214          try (PoolCleaner cleaner = cleaner(p)) {
215              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
216 <                long startTime = System.nanoTime();
217 <                int cycles = 10;
216 >                final long startTime = System.nanoTime();
217 >                final int cycles = 8;
218                  final CountDownLatch done = new CountDownLatch(cycles);
219 <                Runnable task = new CheckedRunnable() {
219 >                final Runnable task = new CheckedRunnable() {
220                      public void realRun() { done.countDown(); }};
221 <                ScheduledFuture h =
221 >                final ScheduledFuture periodicTask =
222                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
223 <                await(done);
224 <                h.cancel(true);
225 <                double normalizedTime =
226 <                    (double) millisElapsedSince(startTime) / delay;
227 <                if (normalizedTime >= cycles - 1 &&
228 <                    normalizedTime <= cycles)
223 >                final int totalDelayMillis = (cycles - 1) * delay;
224 >                await(done, totalDelayMillis + LONG_DELAY_MS);
225 >                periodicTask.cancel(true);
226 >                final long elapsedMillis = millisElapsedSince(startTime);
227 >                assertTrue(elapsedMillis >= totalDelayMillis);
228 >                if (elapsedMillis <= cycles * delay)
229                      return;
230 +                // else retry with longer delay
231              }
232              fail("unexpected execution rate");
233          }
234      }
235  
236      /**
237 <     * scheduleWithFixedDelay executes series of tasks with given period
237 >     * scheduleWithFixedDelay executes series of tasks with given period.
238 >     * Eventually, it must hold that each task starts at least delay and at
239 >     * most 2 * delay after the termination of the previous task.
240       */
241      public void testFixedDelaySequence() throws InterruptedException {
242          final CustomExecutor p = new CustomExecutor(1);
243          try (PoolCleaner cleaner = cleaner(p)) {
244              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
245 <                long startTime = System.nanoTime();
246 <                int cycles = 10;
245 >                final long startTime = System.nanoTime();
246 >                final AtomicLong previous = new AtomicLong(startTime);
247 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
248 >                final int cycles = 8;
249                  final CountDownLatch done = new CountDownLatch(cycles);
250 <                Runnable task = new CheckedRunnable() {
251 <                    public void realRun() { done.countDown(); }};
252 <                ScheduledFuture h =
250 >                final int d = delay;
251 >                final Runnable task = new CheckedRunnable() {
252 >                    public void realRun() {
253 >                        long now = System.nanoTime();
254 >                        long elapsedMillis
255 >                            = NANOSECONDS.toMillis(now - previous.get());
256 >                        if (done.getCount() == cycles) { // first execution
257 >                            if (elapsedMillis >= d)
258 >                                tryLongerDelay.set(true);
259 >                        } else {
260 >                            assertTrue(elapsedMillis >= d);
261 >                            if (elapsedMillis >= 2 * d)
262 >                                tryLongerDelay.set(true);
263 >                        }
264 >                        previous.set(now);
265 >                        done.countDown();
266 >                    }};
267 >                final ScheduledFuture periodicTask =
268                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
269 <                await(done);
270 <                h.cancel(true);
271 <                double normalizedTime =
272 <                    (double) millisElapsedSince(startTime) / delay;
273 <                if (normalizedTime >= cycles - 1 &&
274 <                    normalizedTime <= cycles)
269 >                final int totalDelayMillis = (cycles - 1) * delay;
270 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
271 >                periodicTask.cancel(true);
272 >                final long elapsedMillis = millisElapsedSince(startTime);
273 >                assertTrue(elapsedMillis >= totalDelayMillis);
274 >                if (!tryLongerDelay.get())
275                      return;
276 +                // else retry with longer delay
277              }
278              fail("unexpected execution rate");
279          }
280      }
281  
282      /**
283 <     * execute(null) throws NPE
283 >     * Submitting null tasks throws NullPointerException
284       */
285 <    public void testExecuteNull() throws InterruptedException {
285 >    public void testNullTaskSubmission() {
286          final CustomExecutor p = new CustomExecutor(1);
287          try (PoolCleaner cleaner = cleaner(p)) {
288 <            try {
260 <                p.execute(null);
261 <                shouldThrow();
262 <            } catch (NullPointerException success) {}
288 >            assertNullTaskSubmissionThrowsNullPointerException(p);
289          }
290      }
291  
292      /**
293 <     * schedule(null) throws NPE
293 >     * Submitted tasks are rejected when shutdown
294       */
295 <    public void testScheduleNull() throws InterruptedException {
296 <        final CustomExecutor p = new CustomExecutor(1);
297 <        try (PoolCleaner cleaner = cleaner(p)) {
298 <            try {
299 <                TrackedCallable callable = null;
300 <                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
301 <                shouldThrow();
302 <            } catch (NullPointerException success) {}
303 <        }
304 <    }
295 >    public void testSubmittedTasksRejectedWhenShutdown() throws InterruptedException {
296 >        final CustomExecutor p = new CustomExecutor(2);
297 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
298 >        final CountDownLatch threadsStarted = new CountDownLatch(p.getCorePoolSize());
299 >        final CountDownLatch done = new CountDownLatch(1);
300 >        final Runnable r = () -> {
301 >            threadsStarted.countDown();
302 >            for (;;) {
303 >                try {
304 >                    done.await();
305 >                    return;
306 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
307 >            }};
308 >        final Callable<Boolean> c = () -> {
309 >            threadsStarted.countDown();
310 >            for (;;) {
311 >                try {
312 >                    done.await();
313 >                    return Boolean.TRUE;
314 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
315 >            }};
316  
317 <    /**
318 <     * execute throws RejectedExecutionException if shutdown
319 <     */
320 <    public void testSchedule1_RejectedExecutionException() {
321 <        final CustomExecutor p = new CustomExecutor(1);
322 <        try (PoolCleaner cleaner = cleaner(p)) {
323 <            try {
324 <                p.shutdown();
325 <                p.schedule(new NoOpRunnable(),
289 <                           MEDIUM_DELAY_MS, MILLISECONDS);
290 <                shouldThrow();
291 <            } catch (RejectedExecutionException success) {
292 <            } catch (SecurityException ok) {}
293 <        }
294 <    }
317 >        try (PoolCleaner cleaner = cleaner(p, done)) {
318 >            for (int i = p.getCorePoolSize(); i--> 0; ) {
319 >                switch (rnd.nextInt(4)) {
320 >                case 0: p.execute(r); break;
321 >                case 1: assertFalse(p.submit(r).isDone()); break;
322 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
323 >                case 3: assertFalse(p.submit(c).isDone()); break;
324 >                }
325 >            }
326  
327 <    /**
328 <     * schedule throws RejectedExecutionException if shutdown
298 <     */
299 <    public void testSchedule2_RejectedExecutionException() {
300 <        final CustomExecutor p = new CustomExecutor(1);
301 <        try (PoolCleaner cleaner = cleaner(p)) {
302 <            try {
303 <                p.shutdown();
304 <                p.schedule(new NoOpCallable(),
305 <                           MEDIUM_DELAY_MS, MILLISECONDS);
306 <                shouldThrow();
307 <            } catch (RejectedExecutionException success) {
308 <            } catch (SecurityException ok) {}
309 <        }
310 <    }
327 >            // ScheduledThreadPoolExecutor has an unbounded queue, so never saturated.
328 >            await(threadsStarted);
329  
330 <    /**
331 <     * schedule callable throws RejectedExecutionException if shutdown
332 <     */
315 <    public void testSchedule3_RejectedExecutionException() {
316 <        final CustomExecutor p = new CustomExecutor(1);
317 <        try (PoolCleaner cleaner = cleaner(p)) {
318 <            try {
330 >            if (rnd.nextBoolean())
331 >                p.shutdownNow();
332 >            else
333                  p.shutdown();
334 <                p.schedule(new NoOpCallable(),
335 <                           MEDIUM_DELAY_MS, MILLISECONDS);
336 <                shouldThrow();
323 <            } catch (RejectedExecutionException success) {
324 <            } catch (SecurityException ok) {}
325 <        }
326 <    }
334 >            // Pool is shutdown, but not yet terminated
335 >            assertTaskSubmissionsAreRejected(p);
336 >            assertFalse(p.isTerminated());
337  
338 <    /**
339 <     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
330 <     */
331 <    public void testScheduleAtFixedRate1_RejectedExecutionException() {
332 <        final CustomExecutor p = new CustomExecutor(1);
333 <        try (PoolCleaner cleaner = cleaner(p)) {
334 <            try {
335 <                p.shutdown();
336 <                p.scheduleAtFixedRate(new NoOpRunnable(),
337 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
338 <                shouldThrow();
339 <            } catch (RejectedExecutionException success) {
340 <            } catch (SecurityException ok) {}
341 <        }
342 <    }
338 >            done.countDown();   // release blocking tasks
339 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
340  
341 <    /**
345 <     * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
346 <     */
347 <    public void testScheduleWithFixedDelay1_RejectedExecutionException() {
348 <        final CustomExecutor p = new CustomExecutor(1);
349 <        try (PoolCleaner cleaner = cleaner(p)) {
350 <            try {
351 <                p.shutdown();
352 <                p.scheduleWithFixedDelay(new NoOpRunnable(),
353 <                                         MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
354 <                shouldThrow();
355 <            } catch (RejectedExecutionException success) {
356 <            } catch (SecurityException ok) {}
341 >            assertTaskSubmissionsAreRejected(p);
342          }
343 +        assertEquals(p.getCorePoolSize(), p.getCompletedTaskCount());
344      }
345  
346      /**
# Line 393 | Line 379 | public class ScheduledExecutorSubclassTe
379                  public void realRun() throws InterruptedException {
380                      threadStarted.countDown();
381                      assertEquals(0, p.getCompletedTaskCount());
382 <                    threadProceed.await();
382 >                    await(threadProceed);
383                      threadDone.countDown();
384                  }});
385              await(threadStarted);
386              assertEquals(0, p.getCompletedTaskCount());
387              threadProceed.countDown();
388 <            threadDone.await();
388 >            await(threadDone);
389              long startTime = System.nanoTime();
390              while (p.getCompletedTaskCount() != 1) {
391                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 760 | Line 746 | public class ScheduledExecutorSubclassTe
746       * - setExecuteExistingDelayedTasksAfterShutdownPolicy
747       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
748       */
749 +    @SuppressWarnings("FutureReturnValueIgnored")
750      public void testShutdown_cancellation() throws Exception {
751 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
765 <        for (Boolean policy : allBooleans)
766 <    {
767 <        final int poolSize = 2;
751 >        final int poolSize = 4;
752          final CustomExecutor p = new CustomExecutor(poolSize);
753 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
754 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
755 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
756 <        if (policy != null) {
757 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
758 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
759 <            p.setRemoveOnCancelPolicy(policy);
760 <        }
753 >        final BlockingQueue<Runnable> q = p.getQueue();
754 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
755 >        final long delay = rnd.nextInt(2);
756 >        final int rounds = rnd.nextInt(1, 3);
757 >        final boolean effectiveDelayedPolicy;
758 >        final boolean effectivePeriodicPolicy;
759 >        final boolean effectiveRemovePolicy;
760 >
761 >        if (rnd.nextBoolean())
762 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
763 >                effectiveDelayedPolicy = rnd.nextBoolean());
764 >        else
765 >            effectiveDelayedPolicy = true;
766          assertEquals(effectiveDelayedPolicy,
767                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
768 +
769 +        if (rnd.nextBoolean())
770 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
771 +                effectivePeriodicPolicy = rnd.nextBoolean());
772 +        else
773 +            effectivePeriodicPolicy = false;
774          assertEquals(effectivePeriodicPolicy,
775                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
776 +
777 +        if (rnd.nextBoolean())
778 +            p.setRemoveOnCancelPolicy(
779 +                effectiveRemovePolicy = rnd.nextBoolean());
780 +        else
781 +            effectiveRemovePolicy = false;
782          assertEquals(effectiveRemovePolicy,
783                       p.getRemoveOnCancelPolicy());
784 <        // Strategy: Wedge the pool with poolSize "blocker" threads
784 >
785 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
786 >
787 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
788 >        // then add a second wave that waits in the queue until unblocked.
789          final AtomicInteger ran = new AtomicInteger(0);
790          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
791          final CountDownLatch unblock = new CountDownLatch(1);
792 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
788 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
789 <        Runnable task = new CheckedRunnable() { public void realRun()
790 <                                                    throws InterruptedException {
791 <            poolBlocked.countDown();
792 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
793 <            ran.getAndIncrement();
794 <        }};
795 <        List<Future<?>> blockers = new ArrayList<>();
796 <        List<Future<?>> periodics = new ArrayList<>();
797 <        List<Future<?>> delayeds = new ArrayList<>();
798 <        for (int i = 0; i < poolSize; i++)
799 <            blockers.add(p.submit(task));
800 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
801 <
802 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
803 <                                            1, 1, MILLISECONDS));
804 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
805 <                                               1, 1, MILLISECONDS));
806 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
792 >        final RuntimeException exception = new RuntimeException();
793  
794 <        assertTrue(p.getQueue().containsAll(periodics));
795 <        assertTrue(p.getQueue().containsAll(delayeds));
796 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
797 <        assertTrue(p.isShutdown());
798 <        assertFalse(p.isTerminated());
799 <        for (Future<?> periodic : periodics) {
800 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
815 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
816 <        }
817 <        for (Future<?> delayed : delayeds) {
818 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
819 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
820 <        }
821 <        if (testImplementationDetails) {
822 <            assertEquals(effectivePeriodicPolicy,
823 <                         p.getQueue().containsAll(periodics));
824 <            assertEquals(effectiveDelayedPolicy,
825 <                         p.getQueue().containsAll(delayeds));
826 <        }
827 <        // Release all pool threads
828 <        unblock.countDown();
829 <
830 <        for (Future<?> delayed : delayeds) {
831 <            if (effectiveDelayedPolicy) {
832 <                assertNull(delayed.get());
794 >        class Task implements Runnable {
795 >            public void run() {
796 >                try {
797 >                    ran.getAndIncrement();
798 >                    poolBlocked.countDown();
799 >                    await(unblock);
800 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
801              }
802          }
803 <        if (effectivePeriodicPolicy) {
804 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
805 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
806 <            for (Future<?> periodic : periodics) {
807 <                assertTrue(periodic.cancel(false));
808 <                assertTrue(periodic.isCancelled());
809 <                assertTrue(periodic.isDone());
803 >
804 >        class PeriodicTask extends Task {
805 >            PeriodicTask(int rounds) { this.rounds = rounds; }
806 >            int rounds;
807 >            public void run() {
808 >                if (--rounds == 0) super.run();
809 >                // throw exception to surely terminate this periodic task,
810 >                // but in a separate execution and in a detectable way.
811 >                if (rounds == -1) throw exception;
812              }
813          }
814 +
815 +        Runnable task = new Task();
816 +
817 +        List<Future<?>> immediates = new ArrayList<>();
818 +        List<Future<?>> delayeds   = new ArrayList<>();
819 +        List<Future<?>> periodics  = new ArrayList<>();
820 +
821 +        immediates.add(p.submit(task));
822 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
823 +        periodics.add(p.scheduleAtFixedRate(
824 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
825 +        periodics.add(p.scheduleWithFixedDelay(
826 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
827 +
828 +        await(poolBlocked);
829 +
830 +        assertEquals(poolSize, ran.get());
831 +        assertEquals(poolSize, p.getActiveCount());
832 +        assertTrue(q.isEmpty());
833 +
834 +        // Add second wave of tasks.
835 +        immediates.add(p.submit(task));
836 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
837 +        periodics.add(p.scheduleAtFixedRate(
838 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
839 +        periodics.add(p.scheduleWithFixedDelay(
840 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
841 +
842 +        assertEquals(poolSize, q.size());
843 +        assertEquals(poolSize, ran.get());
844 +
845 +        immediates.forEach(
846 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
847 +
848 +        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
849 +            .forEach(f -> assertFalse(f.isDone()));
850 +
851 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
852 +        assertTrue(p.isShutdown());
853 +        assertTrue(p.isTerminating());
854 +        assertFalse(p.isTerminated());
855 +
856 +        if (rnd.nextBoolean())
857 +            assertThrows(
858 +                RejectedExecutionException.class,
859 +                () -> p.submit(task),
860 +                () -> p.schedule(task, 1, SECONDS),
861 +                () -> p.scheduleAtFixedRate(
862 +                    new PeriodicTask(1), 1, 1, SECONDS),
863 +                () -> p.scheduleWithFixedDelay(
864 +                    new PeriodicTask(2), 1, 1, SECONDS));
865 +
866 +        assertTrue(q.contains(immediates.get(1)));
867 +        assertTrue(!effectiveDelayedPolicy
868 +                   ^ q.contains(delayeds.get(1)));
869 +        assertTrue(!effectivePeriodicPolicy
870 +                   ^ q.containsAll(periodics.subList(2, 4)));
871 +
872 +        immediates.forEach(f -> assertFalse(f.isDone()));
873 +
874 +        assertFalse(delayeds.get(0).isDone());
875 +        if (effectiveDelayedPolicy)
876 +            assertFalse(delayeds.get(1).isDone());
877 +        else
878 +            assertTrue(delayeds.get(1).isCancelled());
879 +
880 +        if (effectivePeriodicPolicy)
881 +            periodics.forEach(
882 +                f -> {
883 +                    assertFalse(f.isDone());
884 +                    if (!periodicTasksContinue) {
885 +                        assertTrue(f.cancel(false));
886 +                        assertTrue(f.isCancelled());
887 +                    }
888 +                });
889 +        else {
890 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
891 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
892 +        }
893 +
894 +        unblock.countDown();    // Release all pool threads
895 +
896          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
897 +        assertFalse(p.isTerminating());
898          assertTrue(p.isTerminated());
899 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
900 <    }}
899 >
900 >        assertTrue(q.isEmpty());
901 >
902 >        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
903 >            .forEach(f -> assertTrue(f.isDone()));
904 >
905 >        for (Future<?> f : immediates) assertNull(f.get());
906 >
907 >        assertNull(delayeds.get(0).get());
908 >        if (effectiveDelayedPolicy)
909 >            assertNull(delayeds.get(1).get());
910 >        else
911 >            assertTrue(delayeds.get(1).isCancelled());
912 >
913 >        if (periodicTasksContinue)
914 >            periodics.forEach(
915 >                f -> {
916 >                    try { f.get(); }
917 >                    catch (ExecutionException success) {
918 >                        assertSame(exception, success.getCause());
919 >                    }
920 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
921 >                });
922 >        else
923 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
924 >
925 >        assertEquals(poolSize + 1
926 >                     + (effectiveDelayedPolicy ? 1 : 0)
927 >                     + (periodicTasksContinue ? 2 : 0),
928 >                     ran.get());
929 >    }
930  
931      /**
932       * completed submit of callable returns result
# Line 896 | Line 978 | public class ScheduledExecutorSubclassTe
978      }
979  
980      /**
981 <     * invokeAny(empty collection) throws IAE
981 >     * invokeAny(empty collection) throws IllegalArgumentException
982       */
983      public void testInvokeAny2() throws Exception {
984          final ExecutorService e = new CustomExecutor(2);
# Line 915 | Line 997 | public class ScheduledExecutorSubclassTe
997          final CountDownLatch latch = new CountDownLatch(1);
998          final ExecutorService e = new CustomExecutor(2);
999          try (PoolCleaner cleaner = cleaner(e)) {
1000 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1000 >            List<Callable<String>> l = new ArrayList<>();
1001              l.add(latchAwaitingStringTask(latch));
1002              l.add(null);
1003              try {
# Line 932 | Line 1014 | public class ScheduledExecutorSubclassTe
1014      public void testInvokeAny4() throws Exception {
1015          final ExecutorService e = new CustomExecutor(2);
1016          try (PoolCleaner cleaner = cleaner(e)) {
1017 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1017 >            List<Callable<String>> l = new ArrayList<>();
1018              l.add(new NPETask());
1019              try {
1020                  e.invokeAny(l);
# Line 949 | Line 1031 | public class ScheduledExecutorSubclassTe
1031      public void testInvokeAny5() throws Exception {
1032          final ExecutorService e = new CustomExecutor(2);
1033          try (PoolCleaner cleaner = cleaner(e)) {
1034 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1034 >            List<Callable<String>> l = new ArrayList<>();
1035              l.add(new StringTask());
1036              l.add(new StringTask());
1037              String result = e.invokeAny(l);
# Line 971 | Line 1053 | public class ScheduledExecutorSubclassTe
1053      }
1054  
1055      /**
1056 <     * invokeAll(empty collection) returns empty collection
1056 >     * invokeAll(empty collection) returns empty list
1057       */
1058      public void testInvokeAll2() throws Exception {
1059          final ExecutorService e = new CustomExecutor(2);
1060 +        final Collection<Callable<String>> emptyCollection
1061 +            = Collections.emptyList();
1062          try (PoolCleaner cleaner = cleaner(e)) {
1063 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1063 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1064              assertTrue(r.isEmpty());
1065          }
1066      }
# Line 987 | Line 1071 | public class ScheduledExecutorSubclassTe
1071      public void testInvokeAll3() throws Exception {
1072          final ExecutorService e = new CustomExecutor(2);
1073          try (PoolCleaner cleaner = cleaner(e)) {
1074 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1074 >            List<Callable<String>> l = new ArrayList<>();
1075              l.add(new StringTask());
1076              l.add(null);
1077              try {
# Line 1003 | Line 1087 | public class ScheduledExecutorSubclassTe
1087      public void testInvokeAll4() throws Exception {
1088          final ExecutorService e = new CustomExecutor(2);
1089          try (PoolCleaner cleaner = cleaner(e)) {
1090 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1090 >            List<Callable<String>> l = new ArrayList<>();
1091              l.add(new NPETask());
1092              List<Future<String>> futures = e.invokeAll(l);
1093              assertEquals(1, futures.size());
# Line 1022 | Line 1106 | public class ScheduledExecutorSubclassTe
1106      public void testInvokeAll5() throws Exception {
1107          final ExecutorService e = new CustomExecutor(2);
1108          try (PoolCleaner cleaner = cleaner(e)) {
1109 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1109 >            List<Callable<String>> l = new ArrayList<>();
1110              l.add(new StringTask());
1111              l.add(new StringTask());
1112              List<Future<String>> futures = e.invokeAll(l);
# Line 1039 | Line 1123 | public class ScheduledExecutorSubclassTe
1123          final ExecutorService e = new CustomExecutor(2);
1124          try (PoolCleaner cleaner = cleaner(e)) {
1125              try {
1126 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1126 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1127                  shouldThrow();
1128              } catch (NullPointerException success) {}
1129          }
# Line 1051 | Line 1135 | public class ScheduledExecutorSubclassTe
1135      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1136          final ExecutorService e = new CustomExecutor(2);
1137          try (PoolCleaner cleaner = cleaner(e)) {
1138 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1138 >            List<Callable<String>> l = new ArrayList<>();
1139              l.add(new StringTask());
1140              try {
1141 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1141 >                e.invokeAny(l, randomTimeout(), null);
1142                  shouldThrow();
1143              } catch (NullPointerException success) {}
1144          }
1145      }
1146  
1147      /**
1148 <     * timed invokeAny(empty collection) throws IAE
1148 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1149       */
1150      public void testTimedInvokeAny2() throws Exception {
1151          final ExecutorService e = new CustomExecutor(2);
1152 +        final Collection<Callable<String>> emptyCollection
1153 +            = Collections.emptyList();
1154          try (PoolCleaner cleaner = cleaner(e)) {
1155              try {
1156 <                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1156 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1157                  shouldThrow();
1158              } catch (IllegalArgumentException success) {}
1159          }
# Line 1080 | Line 1166 | public class ScheduledExecutorSubclassTe
1166          CountDownLatch latch = new CountDownLatch(1);
1167          final ExecutorService e = new CustomExecutor(2);
1168          try (PoolCleaner cleaner = cleaner(e)) {
1169 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1169 >            List<Callable<String>> l = new ArrayList<>();
1170              l.add(latchAwaitingStringTask(latch));
1171              l.add(null);
1172              try {
1173 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1173 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1174                  shouldThrow();
1175              } catch (NullPointerException success) {}
1176              latch.countDown();
# Line 1098 | Line 1184 | public class ScheduledExecutorSubclassTe
1184          final ExecutorService e = new CustomExecutor(2);
1185          try (PoolCleaner cleaner = cleaner(e)) {
1186              long startTime = System.nanoTime();
1187 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1187 >            List<Callable<String>> l = new ArrayList<>();
1188              l.add(new NPETask());
1189              try {
1190                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1117 | Line 1203 | public class ScheduledExecutorSubclassTe
1203          final ExecutorService e = new CustomExecutor(2);
1204          try (PoolCleaner cleaner = cleaner(e)) {
1205              long startTime = System.nanoTime();
1206 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1206 >            List<Callable<String>> l = new ArrayList<>();
1207              l.add(new StringTask());
1208              l.add(new StringTask());
1209              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1127 | Line 1213 | public class ScheduledExecutorSubclassTe
1213      }
1214  
1215      /**
1216 <     * timed invokeAll(null) throws NPE
1216 >     * timed invokeAll(null) throws NullPointerException
1217       */
1218      public void testTimedInvokeAll1() throws Exception {
1219          final ExecutorService e = new CustomExecutor(2);
1220          try (PoolCleaner cleaner = cleaner(e)) {
1221              try {
1222 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1222 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1223                  shouldThrow();
1224              } catch (NullPointerException success) {}
1225          }
1226      }
1227  
1228      /**
1229 <     * timed invokeAll(,,null) throws NPE
1229 >     * timed invokeAll(,,null) throws NullPointerException
1230       */
1231      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1232          final ExecutorService e = new CustomExecutor(2);
1233          try (PoolCleaner cleaner = cleaner(e)) {
1234 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1234 >            List<Callable<String>> l = new ArrayList<>();
1235              l.add(new StringTask());
1236              try {
1237 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1237 >                e.invokeAll(l, randomTimeout(), null);
1238                  shouldThrow();
1239              } catch (NullPointerException success) {}
1240          }
1241      }
1242  
1243      /**
1244 <     * timed invokeAll(empty collection) returns empty collection
1244 >     * timed invokeAll(empty collection) returns empty list
1245       */
1246      public void testTimedInvokeAll2() throws Exception {
1247          final ExecutorService e = new CustomExecutor(2);
1248 +        final Collection<Callable<String>> emptyCollection
1249 +            = Collections.emptyList();
1250          try (PoolCleaner cleaner = cleaner(e)) {
1251 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1251 >            List<Future<String>> r =
1252 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1253              assertTrue(r.isEmpty());
1254          }
1255      }
# Line 1171 | Line 1260 | public class ScheduledExecutorSubclassTe
1260      public void testTimedInvokeAll3() throws Exception {
1261          final ExecutorService e = new CustomExecutor(2);
1262          try (PoolCleaner cleaner = cleaner(e)) {
1263 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1263 >            List<Callable<String>> l = new ArrayList<>();
1264              l.add(new StringTask());
1265              l.add(null);
1266              try {
1267 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1267 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1268                  shouldThrow();
1269              } catch (NullPointerException success) {}
1270          }
# Line 1186 | Line 1275 | public class ScheduledExecutorSubclassTe
1275       */
1276      public void testTimedInvokeAll4() throws Exception {
1277          final ExecutorService e = new CustomExecutor(2);
1278 +        final Collection<Callable<String>> c = new ArrayList<>();
1279 +        c.add(new NPETask());
1280          try (PoolCleaner cleaner = cleaner(e)) {
1190            List<Callable<String>> l = new ArrayList<Callable<String>>();
1191            l.add(new NPETask());
1281              List<Future<String>> futures =
1282 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1282 >                e.invokeAll(c, LONG_DELAY_MS, MILLISECONDS);
1283              assertEquals(1, futures.size());
1284              try {
1285                  futures.get(0).get();
# Line 1207 | Line 1296 | public class ScheduledExecutorSubclassTe
1296      public void testTimedInvokeAll5() throws Exception {
1297          final ExecutorService e = new CustomExecutor(2);
1298          try (PoolCleaner cleaner = cleaner(e)) {
1299 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1299 >            List<Callable<String>> l = new ArrayList<>();
1300              l.add(new StringTask());
1301              l.add(new StringTask());
1302              List<Future<String>> futures =

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines