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.73 by dl, Tue Jan 26 13:33:06 2021 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 117 | Line 123 | public class ScheduledExecutorSubclassTe
123          final CustomExecutor p = new CustomExecutor(1);
124          try (PoolCleaner cleaner = cleaner(p, done)) {
125              final long startTime = System.nanoTime();
126 <            Callable task = new CheckedCallable<Boolean>() {
126 >            Callable<Boolean> task = new CheckedCallable<Boolean>() {
127                  public Boolean realCall() {
128                      done.countDown();
129                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
130                      return Boolean.TRUE;
131                  }};
132 <            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
132 >            Future<Boolean> f = p.schedule(task, timeoutMillis(), MILLISECONDS);
133              assertSame(Boolean.TRUE, f.get());
134              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
135          }
# Line 142 | Line 148 | public class ScheduledExecutorSubclassTe
148                      done.countDown();
149                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
150                  }};
151 <            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
151 >            Future<?> f = p.schedule(task, timeoutMillis(), MILLISECONDS);
152              await(done);
153              assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
154              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
# Line 162 | Line 168 | public class ScheduledExecutorSubclassTe
168                      done.countDown();
169                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
170                  }};
171 <            ScheduledFuture f =
171 >            ScheduledFuture<?> f =
172                  p.scheduleAtFixedRate(task, timeoutMillis(),
173                                        LONG_DELAY_MS, MILLISECONDS);
174              await(done);
# Line 184 | Line 190 | public class ScheduledExecutorSubclassTe
190                      done.countDown();
191                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
192                  }};
193 <            ScheduledFuture f =
193 >            ScheduledFuture<?> f =
194                  p.scheduleWithFixedDelay(task, timeoutMillis(),
195                                           LONG_DELAY_MS, MILLISECONDS);
196              await(done);
# 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 605 | Line 591 | public class ScheduledExecutorSubclassTe
591          final ScheduledThreadPoolExecutor p = new CustomExecutor(1);
592          try (PoolCleaner cleaner = cleaner(p, done)) {
593              final CountDownLatch threadStarted = new CountDownLatch(1);
594 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
594 >            @SuppressWarnings("unchecked")
595 >            ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
596              for (int i = 0; i < tasks.length; i++) {
597                  Runnable r = new CheckedRunnable() {
598                      public void realRun() throws InterruptedException {
# Line 628 | Line 615 | public class ScheduledExecutorSubclassTe
615          final CountDownLatch done = new CountDownLatch(1);
616          final ScheduledThreadPoolExecutor p = new CustomExecutor(1);
617          try (PoolCleaner cleaner = cleaner(p, done)) {
618 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
618 >            @SuppressWarnings("unchecked")
619 >            ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
620              final CountDownLatch threadStarted = new CountDownLatch(1);
621              for (int i = 0; i < tasks.length; i++) {
622                  Runnable r = new CheckedRunnable() {
# Line 656 | Line 644 | public class ScheduledExecutorSubclassTe
644       * purge removes cancelled tasks from the queue
645       */
646      public void testPurge() throws InterruptedException {
647 <        final ScheduledFuture[] tasks = new ScheduledFuture[5];
647 >        @SuppressWarnings("unchecked")
648 >        ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
649          final Runnable releaser = new Runnable() { public void run() {
650 <            for (ScheduledFuture task : tasks)
650 >            for (ScheduledFuture<?> task : tasks)
651                  if (task != null) task.cancel(true); }};
652          final CustomExecutor p = new CustomExecutor(1);
653          try (PoolCleaner cleaner = cleaner(p, releaser)) {
654              for (int i = 0; i < tasks.length; i++)
655 <                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
655 >                tasks[i] = p.schedule(possiblyInterruptedRunnable(SMALL_DELAY_MS),
656                                        LONG_DELAY_MS, MILLISECONDS);
657              int max = tasks.length;
658              if (tasks[4].cancel(true)) --max;
# Line 694 | Line 683 | public class ScheduledExecutorSubclassTe
683          Runnable waiter = new CheckedRunnable() { public void realRun() {
684              threadsStarted.countDown();
685              try {
686 <                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
686 >                MILLISECONDS.sleep(LONGER_DELAY_MS);
687              } catch (InterruptedException success) {}
688              ran.getAndIncrement();
689          }};
# Line 724 | Line 713 | public class ScheduledExecutorSubclassTe
713       */
714      public void testShutdownNow_delayedTasks() throws InterruptedException {
715          final CustomExecutor p = new CustomExecutor(1);
716 <        List<ScheduledFuture> tasks = new ArrayList<>();
716 >        List<ScheduledFuture<?>> tasks = new ArrayList<>();
717          for (int i = 0; i < 3; i++) {
718              Runnable r = new NoOpRunnable();
719              tasks.add(p.schedule(r, 9, SECONDS));
# Line 732 | Line 721 | public class ScheduledExecutorSubclassTe
721              tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
722          }
723          if (testImplementationDetails)
724 <            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
724 >            assertEquals(new HashSet<Object>(tasks), new HashSet<Object>(p.getQueue()));
725          final List<Runnable> queuedTasks;
726          try {
727              queuedTasks = p.shutdownNow();
# Line 742 | Line 731 | public class ScheduledExecutorSubclassTe
731          assertTrue(p.isShutdown());
732          assertTrue(p.getQueue().isEmpty());
733          if (testImplementationDetails)
734 <            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
734 >            assertEquals(new HashSet<Object>(tasks), new HashSet<Object>(queuedTasks));
735          assertEquals(tasks.size(), queuedTasks.size());
736 <        for (ScheduledFuture task : tasks) {
736 >        for (ScheduledFuture<?> task : tasks) {
737              assertFalse(((CustomTask)task).ran);
738              assertFalse(task.isDone());
739              assertFalse(task.isCancelled());
# Line 760 | Line 749 | public class ScheduledExecutorSubclassTe
749       * - setExecuteExistingDelayedTasksAfterShutdownPolicy
750       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
751       */
752 +    @SuppressWarnings("FutureReturnValueIgnored")
753      public void testShutdown_cancellation() throws Exception {
754 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
765 <        for (Boolean policy : allBooleans)
766 <    {
767 <        final int poolSize = 2;
754 >        final int poolSize = 4;
755          final CustomExecutor p = new CustomExecutor(poolSize);
756 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
757 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
758 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
759 <        if (policy != null) {
760 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
761 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
762 <            p.setRemoveOnCancelPolicy(policy);
763 <        }
756 >        final BlockingQueue<Runnable> q = p.getQueue();
757 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
758 >        final long delay = rnd.nextInt(2);
759 >        final int rounds = rnd.nextInt(1, 3);
760 >        final boolean effectiveDelayedPolicy;
761 >        final boolean effectivePeriodicPolicy;
762 >        final boolean effectiveRemovePolicy;
763 >
764 >        if (rnd.nextBoolean())
765 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
766 >                effectiveDelayedPolicy = rnd.nextBoolean());
767 >        else
768 >            effectiveDelayedPolicy = true;
769          assertEquals(effectiveDelayedPolicy,
770                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
771 +
772 +        if (rnd.nextBoolean())
773 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
774 +                effectivePeriodicPolicy = rnd.nextBoolean());
775 +        else
776 +            effectivePeriodicPolicy = false;
777          assertEquals(effectivePeriodicPolicy,
778                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
779 +
780 +        if (rnd.nextBoolean())
781 +            p.setRemoveOnCancelPolicy(
782 +                effectiveRemovePolicy = rnd.nextBoolean());
783 +        else
784 +            effectiveRemovePolicy = false;
785          assertEquals(effectiveRemovePolicy,
786                       p.getRemoveOnCancelPolicy());
787 <        // Strategy: Wedge the pool with poolSize "blocker" threads
787 >
788 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
789 >
790 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
791 >        // then add a second wave that waits in the queue until unblocked.
792          final AtomicInteger ran = new AtomicInteger(0);
793          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
794          final CountDownLatch unblock = new CountDownLatch(1);
795 <        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));
795 >        final RuntimeException exception = new RuntimeException();
796  
797 <        assertTrue(p.getQueue().containsAll(periodics));
798 <        assertTrue(p.getQueue().containsAll(delayeds));
799 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
800 <        assertTrue(p.isShutdown());
801 <        assertFalse(p.isTerminated());
802 <        for (Future<?> periodic : periodics) {
803 <            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());
797 >        class Task implements Runnable {
798 >            public void run() {
799 >                try {
800 >                    ran.getAndIncrement();
801 >                    poolBlocked.countDown();
802 >                    await(unblock);
803 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
804              }
805          }
806 <        if (effectivePeriodicPolicy) {
807 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
808 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
809 <            for (Future<?> periodic : periodics) {
810 <                assertTrue(periodic.cancel(false));
811 <                assertTrue(periodic.isCancelled());
812 <                assertTrue(periodic.isDone());
806 >
807 >        class PeriodicTask extends Task {
808 >            PeriodicTask(int rounds) { this.rounds = rounds; }
809 >            int rounds;
810 >            public void run() {
811 >                if (--rounds == 0) super.run();
812 >                // throw exception to surely terminate this periodic task,
813 >                // but in a separate execution and in a detectable way.
814 >                if (rounds == -1) throw exception;
815              }
816          }
817 +
818 +        Runnable task = new Task();
819 +
820 +        List<Future<?>> immediates = new ArrayList<>();
821 +        List<Future<?>> delayeds   = new ArrayList<>();
822 +        List<Future<?>> periodics  = new ArrayList<>();
823 +
824 +        immediates.add(p.submit(task));
825 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
826 +        periodics.add(p.scheduleAtFixedRate(
827 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
828 +        periodics.add(p.scheduleWithFixedDelay(
829 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
830 +
831 +        await(poolBlocked);
832 +
833 +        assertEquals(poolSize, ran.get());
834 +        assertEquals(poolSize, p.getActiveCount());
835 +        assertTrue(q.isEmpty());
836 +
837 +        // Add second wave of tasks.
838 +        immediates.add(p.submit(task));
839 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
840 +        periodics.add(p.scheduleAtFixedRate(
841 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
842 +        periodics.add(p.scheduleWithFixedDelay(
843 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
844 +
845 +        assertEquals(poolSize, q.size());
846 +        assertEquals(poolSize, ran.get());
847 +
848 +        immediates.forEach(
849 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
850 +
851 +        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
852 +            .forEach(f -> assertFalse(f.isDone()));
853 +
854 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
855 +        assertTrue(p.isShutdown());
856 +        assertTrue(p.isTerminating());
857 +        assertFalse(p.isTerminated());
858 +
859 +        if (rnd.nextBoolean())
860 +            assertThrows(
861 +                RejectedExecutionException.class,
862 +                () -> p.submit(task),
863 +                () -> p.schedule(task, 1, SECONDS),
864 +                () -> p.scheduleAtFixedRate(
865 +                    new PeriodicTask(1), 1, 1, SECONDS),
866 +                () -> p.scheduleWithFixedDelay(
867 +                    new PeriodicTask(2), 1, 1, SECONDS));
868 +
869 +        assertTrue(q.contains(immediates.get(1)));
870 +        assertTrue(!effectiveDelayedPolicy
871 +                   ^ q.contains(delayeds.get(1)));
872 +        assertTrue(!effectivePeriodicPolicy
873 +                   ^ q.containsAll(periodics.subList(2, 4)));
874 +
875 +        immediates.forEach(f -> assertFalse(f.isDone()));
876 +
877 +        assertFalse(delayeds.get(0).isDone());
878 +        if (effectiveDelayedPolicy)
879 +            assertFalse(delayeds.get(1).isDone());
880 +        else
881 +            assertTrue(delayeds.get(1).isCancelled());
882 +
883 +        if (effectivePeriodicPolicy)
884 +            periodics.forEach(
885 +                f -> {
886 +                    assertFalse(f.isDone());
887 +                    if (!periodicTasksContinue) {
888 +                        assertTrue(f.cancel(false));
889 +                        assertTrue(f.isCancelled());
890 +                    }
891 +                });
892 +        else {
893 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
894 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
895 +        }
896 +
897 +        unblock.countDown();    // Release all pool threads
898 +
899          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
900 +        assertFalse(p.isTerminating());
901          assertTrue(p.isTerminated());
902 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
903 <    }}
902 >
903 >        assertTrue(q.isEmpty());
904 >
905 >        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
906 >            .forEach(f -> assertTrue(f.isDone()));
907 >
908 >        for (Future<?> f : immediates) assertNull(f.get());
909 >
910 >        assertNull(delayeds.get(0).get());
911 >        if (effectiveDelayedPolicy)
912 >            assertNull(delayeds.get(1).get());
913 >        else
914 >            assertTrue(delayeds.get(1).isCancelled());
915 >
916 >        if (periodicTasksContinue)
917 >            periodics.forEach(
918 >                f -> {
919 >                    try { f.get(); }
920 >                    catch (ExecutionException success) {
921 >                        assertSame(exception, success.getCause());
922 >                    }
923 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
924 >                });
925 >        else
926 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
927 >
928 >        assertEquals(poolSize + 1
929 >                     + (effectiveDelayedPolicy ? 1 : 0)
930 >                     + (periodicTasksContinue ? 2 : 0),
931 >                     ran.get());
932 >    }
933  
934      /**
935       * completed submit of callable returns result
# Line 896 | Line 981 | public class ScheduledExecutorSubclassTe
981      }
982  
983      /**
984 <     * invokeAny(empty collection) throws IAE
984 >     * invokeAny(empty collection) throws IllegalArgumentException
985       */
986      public void testInvokeAny2() throws Exception {
987          final ExecutorService e = new CustomExecutor(2);
# Line 915 | Line 1000 | public class ScheduledExecutorSubclassTe
1000          final CountDownLatch latch = new CountDownLatch(1);
1001          final ExecutorService e = new CustomExecutor(2);
1002          try (PoolCleaner cleaner = cleaner(e)) {
1003 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1003 >            List<Callable<String>> l = new ArrayList<>();
1004              l.add(latchAwaitingStringTask(latch));
1005              l.add(null);
1006              try {
# Line 932 | Line 1017 | public class ScheduledExecutorSubclassTe
1017      public void testInvokeAny4() throws Exception {
1018          final ExecutorService e = new CustomExecutor(2);
1019          try (PoolCleaner cleaner = cleaner(e)) {
1020 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1020 >            List<Callable<String>> l = new ArrayList<>();
1021              l.add(new NPETask());
1022              try {
1023                  e.invokeAny(l);
# Line 949 | Line 1034 | public class ScheduledExecutorSubclassTe
1034      public void testInvokeAny5() throws Exception {
1035          final ExecutorService e = new CustomExecutor(2);
1036          try (PoolCleaner cleaner = cleaner(e)) {
1037 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1037 >            List<Callable<String>> l = new ArrayList<>();
1038              l.add(new StringTask());
1039              l.add(new StringTask());
1040              String result = e.invokeAny(l);
# Line 971 | Line 1056 | public class ScheduledExecutorSubclassTe
1056      }
1057  
1058      /**
1059 <     * invokeAll(empty collection) returns empty collection
1059 >     * invokeAll(empty collection) returns empty list
1060       */
1061      public void testInvokeAll2() throws Exception {
1062          final ExecutorService e = new CustomExecutor(2);
1063 +        final Collection<Callable<String>> emptyCollection
1064 +            = Collections.emptyList();
1065          try (PoolCleaner cleaner = cleaner(e)) {
1066 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1066 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1067              assertTrue(r.isEmpty());
1068          }
1069      }
# Line 987 | Line 1074 | public class ScheduledExecutorSubclassTe
1074      public void testInvokeAll3() throws Exception {
1075          final ExecutorService e = new CustomExecutor(2);
1076          try (PoolCleaner cleaner = cleaner(e)) {
1077 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1077 >            List<Callable<String>> l = new ArrayList<>();
1078              l.add(new StringTask());
1079              l.add(null);
1080              try {
# Line 1003 | Line 1090 | public class ScheduledExecutorSubclassTe
1090      public void testInvokeAll4() throws Exception {
1091          final ExecutorService e = new CustomExecutor(2);
1092          try (PoolCleaner cleaner = cleaner(e)) {
1093 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1093 >            List<Callable<String>> l = new ArrayList<>();
1094              l.add(new NPETask());
1095              List<Future<String>> futures = e.invokeAll(l);
1096              assertEquals(1, futures.size());
# Line 1022 | Line 1109 | public class ScheduledExecutorSubclassTe
1109      public void testInvokeAll5() throws Exception {
1110          final ExecutorService e = new CustomExecutor(2);
1111          try (PoolCleaner cleaner = cleaner(e)) {
1112 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1112 >            List<Callable<String>> l = new ArrayList<>();
1113              l.add(new StringTask());
1114              l.add(new StringTask());
1115              List<Future<String>> futures = e.invokeAll(l);
# Line 1039 | Line 1126 | public class ScheduledExecutorSubclassTe
1126          final ExecutorService e = new CustomExecutor(2);
1127          try (PoolCleaner cleaner = cleaner(e)) {
1128              try {
1129 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1129 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1130                  shouldThrow();
1131              } catch (NullPointerException success) {}
1132          }
# Line 1051 | Line 1138 | public class ScheduledExecutorSubclassTe
1138      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1139          final ExecutorService e = new CustomExecutor(2);
1140          try (PoolCleaner cleaner = cleaner(e)) {
1141 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1141 >            List<Callable<String>> l = new ArrayList<>();
1142              l.add(new StringTask());
1143              try {
1144 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1144 >                e.invokeAny(l, randomTimeout(), null);
1145                  shouldThrow();
1146              } catch (NullPointerException success) {}
1147          }
1148      }
1149  
1150      /**
1151 <     * timed invokeAny(empty collection) throws IAE
1151 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1152       */
1153      public void testTimedInvokeAny2() throws Exception {
1154          final ExecutorService e = new CustomExecutor(2);
1155 +        final Collection<Callable<String>> emptyCollection
1156 +            = Collections.emptyList();
1157          try (PoolCleaner cleaner = cleaner(e)) {
1158              try {
1159 <                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1159 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1160                  shouldThrow();
1161              } catch (IllegalArgumentException success) {}
1162          }
# Line 1080 | Line 1169 | public class ScheduledExecutorSubclassTe
1169          CountDownLatch latch = new CountDownLatch(1);
1170          final ExecutorService e = new CustomExecutor(2);
1171          try (PoolCleaner cleaner = cleaner(e)) {
1172 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1172 >            List<Callable<String>> l = new ArrayList<>();
1173              l.add(latchAwaitingStringTask(latch));
1174              l.add(null);
1175              try {
1176 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1176 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1177                  shouldThrow();
1178              } catch (NullPointerException success) {}
1179              latch.countDown();
# Line 1098 | Line 1187 | public class ScheduledExecutorSubclassTe
1187          final ExecutorService e = new CustomExecutor(2);
1188          try (PoolCleaner cleaner = cleaner(e)) {
1189              long startTime = System.nanoTime();
1190 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1190 >            List<Callable<String>> l = new ArrayList<>();
1191              l.add(new NPETask());
1192              try {
1193                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1117 | Line 1206 | public class ScheduledExecutorSubclassTe
1206          final ExecutorService e = new CustomExecutor(2);
1207          try (PoolCleaner cleaner = cleaner(e)) {
1208              long startTime = System.nanoTime();
1209 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1209 >            List<Callable<String>> l = new ArrayList<>();
1210              l.add(new StringTask());
1211              l.add(new StringTask());
1212              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1127 | Line 1216 | public class ScheduledExecutorSubclassTe
1216      }
1217  
1218      /**
1219 <     * timed invokeAll(null) throws NPE
1219 >     * timed invokeAll(null) throws NullPointerException
1220       */
1221      public void testTimedInvokeAll1() throws Exception {
1222          final ExecutorService e = new CustomExecutor(2);
1223          try (PoolCleaner cleaner = cleaner(e)) {
1224              try {
1225 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1225 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1226                  shouldThrow();
1227              } catch (NullPointerException success) {}
1228          }
1229      }
1230  
1231      /**
1232 <     * timed invokeAll(,,null) throws NPE
1232 >     * timed invokeAll(,,null) throws NullPointerException
1233       */
1234      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1235          final ExecutorService e = new CustomExecutor(2);
1236          try (PoolCleaner cleaner = cleaner(e)) {
1237 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1237 >            List<Callable<String>> l = new ArrayList<>();
1238              l.add(new StringTask());
1239              try {
1240 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1240 >                e.invokeAll(l, randomTimeout(), null);
1241                  shouldThrow();
1242              } catch (NullPointerException success) {}
1243          }
1244      }
1245  
1246      /**
1247 <     * timed invokeAll(empty collection) returns empty collection
1247 >     * timed invokeAll(empty collection) returns empty list
1248       */
1249      public void testTimedInvokeAll2() throws Exception {
1250          final ExecutorService e = new CustomExecutor(2);
1251 +        final Collection<Callable<String>> emptyCollection
1252 +            = Collections.emptyList();
1253          try (PoolCleaner cleaner = cleaner(e)) {
1254 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1254 >            List<Future<String>> r =
1255 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1256              assertTrue(r.isEmpty());
1257          }
1258      }
# Line 1171 | Line 1263 | public class ScheduledExecutorSubclassTe
1263      public void testTimedInvokeAll3() throws Exception {
1264          final ExecutorService e = new CustomExecutor(2);
1265          try (PoolCleaner cleaner = cleaner(e)) {
1266 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1266 >            List<Callable<String>> l = new ArrayList<>();
1267              l.add(new StringTask());
1268              l.add(null);
1269              try {
1270 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1270 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1271                  shouldThrow();
1272              } catch (NullPointerException success) {}
1273          }
# Line 1186 | Line 1278 | public class ScheduledExecutorSubclassTe
1278       */
1279      public void testTimedInvokeAll4() throws Exception {
1280          final ExecutorService e = new CustomExecutor(2);
1281 +        final Collection<Callable<String>> c = new ArrayList<>();
1282 +        c.add(new NPETask());
1283          try (PoolCleaner cleaner = cleaner(e)) {
1190            List<Callable<String>> l = new ArrayList<Callable<String>>();
1191            l.add(new NPETask());
1284              List<Future<String>> futures =
1285 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1285 >                e.invokeAll(c, LONG_DELAY_MS, MILLISECONDS);
1286              assertEquals(1, futures.size());
1287              try {
1288                  futures.get(0).get();
# Line 1207 | Line 1299 | public class ScheduledExecutorSubclassTe
1299      public void testTimedInvokeAll5() throws Exception {
1300          final ExecutorService e = new CustomExecutor(2);
1301          try (PoolCleaner cleaner = cleaner(e)) {
1302 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1302 >            List<Callable<String>> l = new ArrayList<>();
1303              l.add(new StringTask());
1304              l.add(new StringTask());
1305              List<Future<String>> futures =
# Line 1240 | Line 1332 | public class ScheduledExecutorSubclassTe
1332                      p.invokeAll(tasks, timeout, MILLISECONDS);
1333                  assertEquals(tasks.size(), futures.size());
1334                  assertTrue(millisElapsedSince(startTime) >= timeout);
1335 <                for (Future future : futures)
1335 >                for (Future<?> future : futures)
1336                      assertTrue(future.isDone());
1337                  assertTrue(futures.get(1).isCancelled());
1338                  try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines