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

Comparing jsr166/src/test/tck/ScheduledExecutorTest.java (file contents):
Revision 1.76 by jsr166, Thu Oct 8 03:08:37 2015 UTC vs.
Revision 1.87 by jsr166, Sat Mar 25 23:35:15 2017 UTC

# Line 7 | Line 7
7   */
8  
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11   import static java.util.concurrent.TimeUnit.SECONDS;
12  
13   import java.util.ArrayList;
# Line 17 | Line 18 | import java.util.concurrent.Callable;
18   import java.util.concurrent.CancellationException;
19   import java.util.concurrent.CountDownLatch;
20   import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Executors;
21   import java.util.concurrent.ExecutorService;
22   import java.util.concurrent.Future;
23   import java.util.concurrent.RejectedExecutionException;
# Line 25 | Line 25 | import java.util.concurrent.ScheduledFut
25   import java.util.concurrent.ScheduledThreadPoolExecutor;
26   import java.util.concurrent.ThreadFactory;
27   import java.util.concurrent.ThreadPoolExecutor;
28 + import java.util.concurrent.atomic.AtomicBoolean;
29   import java.util.concurrent.atomic.AtomicInteger;
30 + import java.util.concurrent.atomic.AtomicLong;
31  
32   import junit.framework.Test;
33   import junit.framework.TestSuite;
# Line 48 | Line 50 | public class ScheduledExecutorTest exten
50              final Runnable task = new CheckedRunnable() {
51                  public void realRun() { done.countDown(); }};
52              p.execute(task);
53 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
53 >            await(done);
54          }
55      }
56  
# Line 143 | Line 145 | public class ScheduledExecutorTest exten
145      }
146  
147      /**
148 <     * scheduleAtFixedRate executes series of tasks at given rate
148 >     * scheduleAtFixedRate executes series of tasks at given rate.
149 >     * Eventually, it must hold that:
150 >     *   cycles - 1 <= elapsedMillis/delay < cycles
151       */
152      public void testFixedRateSequence() throws InterruptedException {
153          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
154          try (PoolCleaner cleaner = cleaner(p)) {
155              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
156 <                long startTime = System.nanoTime();
157 <                int cycles = 10;
156 >                final long startTime = System.nanoTime();
157 >                final int cycles = 8;
158                  final CountDownLatch done = new CountDownLatch(cycles);
159 <                Runnable task = new CheckedRunnable() {
159 >                final Runnable task = new CheckedRunnable() {
160                      public void realRun() { done.countDown(); }};
161 <                ScheduledFuture h =
161 >                final ScheduledFuture periodicTask =
162                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
163 <                await(done);
164 <                h.cancel(true);
165 <                double normalizedTime =
166 <                    (double) millisElapsedSince(startTime) / delay;
167 <                if (normalizedTime >= cycles - 1 &&
168 <                    normalizedTime <= cycles)
163 >                final int totalDelayMillis = (cycles - 1) * delay;
164 >                await(done, totalDelayMillis + LONG_DELAY_MS);
165 >                periodicTask.cancel(true);
166 >                final long elapsedMillis = millisElapsedSince(startTime);
167 >                assertTrue(elapsedMillis >= totalDelayMillis);
168 >                if (elapsedMillis <= cycles * delay)
169                      return;
170 +                // else retry with longer delay
171              }
172 <            throw new AssertionError("unexpected execution rate");
172 >            fail("unexpected execution rate");
173          }
174      }
175  
176      /**
177 <     * scheduleWithFixedDelay executes series of tasks with given period
177 >     * scheduleWithFixedDelay executes series of tasks with given period.
178 >     * Eventually, it must hold that each task starts at least delay and at
179 >     * most 2 * delay after the termination of the previous task.
180       */
181      public void testFixedDelaySequence() throws InterruptedException {
182          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
183          try (PoolCleaner cleaner = cleaner(p)) {
184              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
185 <                long startTime = System.nanoTime();
186 <                int cycles = 10;
185 >                final long startTime = System.nanoTime();
186 >                final AtomicLong previous = new AtomicLong(startTime);
187 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
188 >                final int cycles = 8;
189                  final CountDownLatch done = new CountDownLatch(cycles);
190 <                Runnable task = new CheckedRunnable() {
191 <                    public void realRun() { done.countDown(); }};
192 <                ScheduledFuture h =
190 >                final int d = delay;
191 >                final Runnable task = new CheckedRunnable() {
192 >                    public void realRun() {
193 >                        long now = System.nanoTime();
194 >                        long elapsedMillis
195 >                            = NANOSECONDS.toMillis(now - previous.get());
196 >                        if (done.getCount() == cycles) { // first execution
197 >                            if (elapsedMillis >= d)
198 >                                tryLongerDelay.set(true);
199 >                        } else {
200 >                            assertTrue(elapsedMillis >= d);
201 >                            if (elapsedMillis >= 2 * d)
202 >                                tryLongerDelay.set(true);
203 >                        }
204 >                        previous.set(now);
205 >                        done.countDown();
206 >                    }};
207 >                final ScheduledFuture periodicTask =
208                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
209 <                await(done);
210 <                h.cancel(true);
211 <                double normalizedTime =
212 <                    (double) millisElapsedSince(startTime) / delay;
213 <                if (normalizedTime >= cycles - 1 &&
214 <                    normalizedTime <= cycles)
209 >                final int totalDelayMillis = (cycles - 1) * delay;
210 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
211 >                periodicTask.cancel(true);
212 >                final long elapsedMillis = millisElapsedSince(startTime);
213 >                assertTrue(elapsedMillis >= totalDelayMillis);
214 >                if (!tryLongerDelay.get())
215                      return;
216 +                // else retry with longer delay
217              }
218 <            throw new AssertionError("unexpected execution rate");
218 >            fail("unexpected execution rate");
219          }
220      }
221  
# Line 337 | Line 362 | public class ScheduledExecutorTest exten
362                  public void realRun() throws InterruptedException {
363                      threadStarted.countDown();
364                      assertEquals(0, p.getCompletedTaskCount());
365 <                    threadProceed.await();
365 >                    await(threadProceed);
366                      threadDone.countDown();
367                  }});
368              await(threadStarted);
369              assertEquals(0, p.getCompletedTaskCount());
370              threadProceed.countDown();
371 <            threadDone.await();
371 >            await(threadDone);
372              long startTime = System.nanoTime();
373              while (p.getCompletedTaskCount() != 1) {
374                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 482 | Line 507 | public class ScheduledExecutorTest exten
507      }
508  
509      /**
510 +     * The default rejected execution handler is AbortPolicy.
511 +     */
512 +    public void testDefaultRejectedExecutionHandler() {
513 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
514 +        try (PoolCleaner cleaner = cleaner(p)) {
515 +            assertTrue(p.getRejectedExecutionHandler()
516 +                       instanceof ThreadPoolExecutor.AbortPolicy);
517 +        }
518 +    }
519 +
520 +    /**
521       * isShutdown is false before shutdown, true after
522       */
523      public void testIsShutdown() {
488
524          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
525 <        try {
526 <            assertFalse(p.isShutdown());
527 <        }
528 <        finally {
529 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
525 >        assertFalse(p.isShutdown());
526 >        try (PoolCleaner cleaner = cleaner(p)) {
527 >            try {
528 >                p.shutdown();
529 >                assertTrue(p.isShutdown());
530 >            } catch (SecurityException ok) {}
531          }
496        assertTrue(p.isShutdown());
532      }
533  
534      /**
# Line 709 | Line 744 | public class ScheduledExecutorTest exten
744       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
745       */
746      public void testShutdown_cancellation() throws Exception {
747 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
748 <        for (Boolean policy : allBooleans)
747 >        final int UNSPECIFIED = 0, YES = 1, NO = 2;
748 >        for (int maybe : new int[] { UNSPECIFIED, YES, NO })
749      {
750          final int poolSize = 2;
751          final ScheduledThreadPoolExecutor p
752              = new ScheduledThreadPoolExecutor(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);
753 >        final boolean effectiveDelayedPolicy  = (maybe != NO);
754 >        final boolean effectivePeriodicPolicy = (maybe == YES);
755 >        final boolean effectiveRemovePolicy   = (maybe == YES);
756 >        if (maybe != UNSPECIFIED) {
757 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(maybe == YES);
758 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(maybe == YES);
759 >            p.setRemoveOnCancelPolicy(maybe == YES);
760          }
761          assertEquals(effectiveDelayedPolicy,
762                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 738 | Line 773 | public class ScheduledExecutorTest exten
773          Runnable task = new CheckedRunnable() { public void realRun()
774                                                      throws InterruptedException {
775              poolBlocked.countDown();
776 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
776 >            await(unblock);
777              ran.getAndIncrement();
778          }};
779          List<Future<?>> blockers = new ArrayList<>();
# Line 746 | Line 781 | public class ScheduledExecutorTest exten
781          List<Future<?>> delayeds = new ArrayList<>();
782          for (int i = 0; i < poolSize; i++)
783              blockers.add(p.submit(task));
784 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
784 >        await(poolBlocked);
785  
786 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
787 <                                            1, 1, MILLISECONDS));
788 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
789 <                                               1, 1, MILLISECONDS));
786 >        periodics.add(p.scheduleAtFixedRate(
787 >                          countDowner(periodicLatch1), 1, 1, MILLISECONDS));
788 >        periodics.add(p.scheduleWithFixedDelay(
789 >                          countDowner(periodicLatch2), 1, 1, MILLISECONDS));
790          delayeds.add(p.schedule(task, 1, MILLISECONDS));
791  
792          assertTrue(p.getQueue().containsAll(periodics));
# Line 773 | Line 808 | public class ScheduledExecutorTest exten
808              assertEquals(effectiveDelayedPolicy,
809                           p.getQueue().containsAll(delayeds));
810          }
811 <        // Release all pool threads
777 <        unblock.countDown();
811 >        unblock.countDown();    // Release all pool threads
812  
813 <        for (Future<?> delayed : delayeds) {
814 <            if (effectiveDelayedPolicy) {
781 <                assertNull(delayed.get());
782 <            }
783 <        }
813 >        if (effectiveDelayedPolicy)
814 >            for (Future<?> delayed : delayeds) assertNull(delayed.get());
815          if (effectivePeriodicPolicy) {
816 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
817 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
816 >            await(periodicLatch1);
817 >            await(periodicLatch2);
818              for (Future<?> periodic : periodics) {
819                  assertTrue(periodic.cancel(false));
820                  assertTrue(periodic.isCancelled());
821                  assertTrue(periodic.isDone());
822              }
823          }
824 +        for (Future<?> blocker : blockers) assertNull(blocker.get());
825          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
826          assertTrue(p.isTerminated());
827 +
828 +        for (Future<?> future : delayeds) {
829 +            assertTrue(effectiveDelayedPolicy ^ future.isCancelled());
830 +            assertTrue(future.isDone());
831 +        }
832 +        for (Future<?> future : periodics)
833 +            assertTrue(future.isCancelled());
834 +        for (Future<?> future : blockers)
835 +            assertNull(future.get());
836          assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
837      }}
838  
# Line 864 | Line 905 | public class ScheduledExecutorTest exten
905          CountDownLatch latch = new CountDownLatch(1);
906          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
907          try (PoolCleaner cleaner = cleaner(e)) {
908 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
908 >            List<Callable<String>> l = new ArrayList<>();
909              l.add(latchAwaitingStringTask(latch));
910              l.add(null);
911              try {
# Line 881 | Line 922 | public class ScheduledExecutorTest exten
922      public void testInvokeAny4() throws Exception {
923          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
924          try (PoolCleaner cleaner = cleaner(e)) {
925 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
925 >            List<Callable<String>> l = new ArrayList<>();
926              l.add(new NPETask());
927              try {
928                  e.invokeAny(l);
# Line 898 | Line 939 | public class ScheduledExecutorTest exten
939      public void testInvokeAny5() throws Exception {
940          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
941          try (PoolCleaner cleaner = cleaner(e)) {
942 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
942 >            List<Callable<String>> l = new ArrayList<>();
943              l.add(new StringTask());
944              l.add(new StringTask());
945              String result = e.invokeAny(l);
# Line 936 | Line 977 | public class ScheduledExecutorTest exten
977      public void testInvokeAll3() throws Exception {
978          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
979          try (PoolCleaner cleaner = cleaner(e)) {
980 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
980 >            List<Callable<String>> l = new ArrayList<>();
981              l.add(new StringTask());
982              l.add(null);
983              try {
# Line 952 | Line 993 | public class ScheduledExecutorTest exten
993      public void testInvokeAll4() throws Exception {
994          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
995          try (PoolCleaner cleaner = cleaner(e)) {
996 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
996 >            List<Callable<String>> l = new ArrayList<>();
997              l.add(new NPETask());
998              List<Future<String>> futures = e.invokeAll(l);
999              assertEquals(1, futures.size());
# Line 971 | Line 1012 | public class ScheduledExecutorTest exten
1012      public void testInvokeAll5() throws Exception {
1013          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1014          try (PoolCleaner cleaner = cleaner(e)) {
1015 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1015 >            List<Callable<String>> l = new ArrayList<>();
1016              l.add(new StringTask());
1017              l.add(new StringTask());
1018              List<Future<String>> futures = e.invokeAll(l);
# Line 1000 | Line 1041 | public class ScheduledExecutorTest exten
1041      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1042          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1043          try (PoolCleaner cleaner = cleaner(e)) {
1044 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1044 >            List<Callable<String>> l = new ArrayList<>();
1045              l.add(new StringTask());
1046              try {
1047                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1029 | Line 1070 | public class ScheduledExecutorTest exten
1070          CountDownLatch latch = new CountDownLatch(1);
1071          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1072          try (PoolCleaner cleaner = cleaner(e)) {
1073 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1073 >            List<Callable<String>> l = new ArrayList<>();
1074              l.add(latchAwaitingStringTask(latch));
1075              l.add(null);
1076              try {
# Line 1047 | Line 1088 | public class ScheduledExecutorTest exten
1088          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1089          try (PoolCleaner cleaner = cleaner(e)) {
1090              long startTime = System.nanoTime();
1091 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1091 >            List<Callable<String>> l = new ArrayList<>();
1092              l.add(new NPETask());
1093              try {
1094                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1066 | Line 1107 | public class ScheduledExecutorTest exten
1107          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1108          try (PoolCleaner cleaner = cleaner(e)) {
1109              long startTime = System.nanoTime();
1110 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1110 >            List<Callable<String>> l = new ArrayList<>();
1111              l.add(new StringTask());
1112              l.add(new StringTask());
1113              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1094 | Line 1135 | public class ScheduledExecutorTest exten
1135      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1136          final ExecutorService e = new ScheduledThreadPoolExecutor(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.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1121 | Line 1162 | public class ScheduledExecutorTest exten
1162      public void testTimedInvokeAll3() throws Exception {
1163          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1164          try (PoolCleaner cleaner = cleaner(e)) {
1165 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1165 >            List<Callable<String>> l = new ArrayList<>();
1166              l.add(new StringTask());
1167              l.add(null);
1168              try {
# Line 1137 | Line 1178 | public class ScheduledExecutorTest exten
1178      public void testTimedInvokeAll4() throws Exception {
1179          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1180          try (PoolCleaner cleaner = cleaner(e)) {
1181 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1181 >            List<Callable<String>> l = new ArrayList<>();
1182              l.add(new NPETask());
1183              List<Future<String>> futures =
1184                  e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1157 | Line 1198 | public class ScheduledExecutorTest exten
1198      public void testTimedInvokeAll5() throws Exception {
1199          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1200          try (PoolCleaner cleaner = cleaner(e)) {
1201 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1201 >            List<Callable<String>> l = new ArrayList<>();
1202              l.add(new StringTask());
1203              l.add(new StringTask());
1204              List<Future<String>> futures =
# Line 1206 | Line 1247 | public class ScheduledExecutorTest exten
1247          }
1248      }
1249  
1250 +    /**
1251 +     * A fixed delay task with overflowing period should not prevent a
1252 +     * one-shot task from executing.
1253 +     * https://bugs.openjdk.java.net/browse/JDK-8051859
1254 +     */
1255 +    public void testScheduleWithFixedDelay_overflow() throws Exception {
1256 +        final CountDownLatch delayedDone = new CountDownLatch(1);
1257 +        final CountDownLatch immediateDone = new CountDownLatch(1);
1258 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1259 +        try (PoolCleaner cleaner = cleaner(p)) {
1260 +            final Runnable immediate = new Runnable() { public void run() {
1261 +                immediateDone.countDown();
1262 +            }};
1263 +            final Runnable delayed = new Runnable() { public void run() {
1264 +                delayedDone.countDown();
1265 +                p.submit(immediate);
1266 +            }};
1267 +            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1268 +            await(delayedDone);
1269 +            await(immediateDone);
1270 +        }
1271 +    }
1272 +
1273   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines