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.39 by dl, Fri May 6 11:22:07 2011 UTC vs.
Revision 1.47 by jsr166, Tue Sep 24 18:35:21 2013 UTC

# Line 10 | Line 10 | import junit.framework.*;
10   import java.util.*;
11   import java.util.concurrent.*;
12   import static java.util.concurrent.TimeUnit.MILLISECONDS;
13 < import java.util.concurrent.atomic.*;
13 > import java.util.concurrent.atomic.AtomicInteger;
14  
15   public class ScheduledExecutorTest extends JSR166TestCase {
16      public static void main(String[] args) {
# Line 20 | Line 20 | public class ScheduledExecutorTest exten
20          return new TestSuite(ScheduledExecutorTest.class);
21      }
22  
23
23      /**
24       * execute successfully executes a runnable
25       */
# Line 39 | Line 38 | public class ScheduledExecutorTest exten
38          }
39      }
40  
42
41      /**
42       * delayed schedule of callable successfully executes after delay
43       */
44      public void testSchedule1() throws Exception {
45          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
46 <        final long t0 = System.nanoTime();
49 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
46 >        final long startTime = System.nanoTime();
47          final CountDownLatch done = new CountDownLatch(1);
48          try {
49              Callable task = new CheckedCallable<Boolean>() {
50                  public Boolean realCall() {
51                      done.countDown();
52 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
52 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
53                      return Boolean.TRUE;
54                  }};
55 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
56 <            assertEquals(Boolean.TRUE, f.get());
57 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
55 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
56 >            assertSame(Boolean.TRUE, f.get());
57 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
58              assertTrue(done.await(0L, MILLISECONDS));
59          } finally {
60              joinPool(p);
# Line 69 | Line 66 | public class ScheduledExecutorTest exten
66       */
67      public void testSchedule3() throws Exception {
68          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
69 <        final long t0 = System.nanoTime();
73 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
69 >        final long startTime = System.nanoTime();
70          final CountDownLatch done = new CountDownLatch(1);
71          try {
72              Runnable task = new CheckedRunnable() {
73                  public void realRun() {
74                      done.countDown();
75 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
75 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76                  }};
77 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
78 <            assertNull(f.get());
79 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
80 <            assertTrue(done.await(0L, MILLISECONDS));
77 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
78 >            await(done);
79 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
80 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
81          } finally {
82              joinPool(p);
83          }
# Line 92 | Line 88 | public class ScheduledExecutorTest exten
88       */
89      public void testSchedule4() throws Exception {
90          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
91 <        final long t0 = System.nanoTime();
96 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
91 >        final long startTime = System.nanoTime();
92          final CountDownLatch done = new CountDownLatch(1);
93          try {
94              Runnable task = new CheckedRunnable() {
95                  public void realRun() {
96                      done.countDown();
97 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
97 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
98                  }};
99              ScheduledFuture f =
100 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
101 <                                      SHORT_DELAY_MS, MILLISECONDS);
102 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
103 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
100 >                p.scheduleAtFixedRate(task, timeoutMillis(),
101 >                                      LONG_DELAY_MS, MILLISECONDS);
102 >            await(done);
103 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
104              f.cancel(true);
105          } finally {
106              joinPool(p);
# Line 115 | Line 110 | public class ScheduledExecutorTest exten
110      /**
111       * scheduleWithFixedDelay executes runnable after given initial delay
112       */
113 <    public void testSchedule5() throws InterruptedException {
113 >    public void testSchedule5() throws Exception {
114          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
115 <        final long t0 = System.nanoTime();
121 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
115 >        final long startTime = System.nanoTime();
116          final CountDownLatch done = new CountDownLatch(1);
117          try {
118              Runnable task = new CheckedRunnable() {
119                  public void realRun() {
120                      done.countDown();
121 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
121 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
122                  }};
123              ScheduledFuture f =
124 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
125 <                                         SHORT_DELAY_MS, MILLISECONDS);
126 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
127 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
124 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
125 >                                         LONG_DELAY_MS, MILLISECONDS);
126 >            await(done);
127 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
128              f.cancel(true);
129          } finally {
130              joinPool(p);
# Line 147 | Line 141 | public class ScheduledExecutorTest exten
141       */
142      public void testFixedRateSequence() throws InterruptedException {
143          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
144 <        RunnableCounter counter = new RunnableCounter();
145 <        ScheduledFuture h =
146 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
147 <        delay(SMALL_DELAY_MS);
148 <        h.cancel(true);
149 <        int c = counter.count.get();
150 <        // By time scaling conventions, we must have at least
151 <        // an execution per SHORT delay, but no more than one SHORT more
152 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
153 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
154 <        joinPool(p);
144 >        try {
145 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
146 >                long startTime = System.nanoTime();
147 >                int cycles = 10;
148 >                final CountDownLatch done = new CountDownLatch(cycles);
149 >                CheckedRunnable task = new CheckedRunnable() {
150 >                    public void realRun() { done.countDown(); }};
151 >                
152 >                ScheduledFuture h =
153 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
154 >                done.await();
155 >                h.cancel(true);
156 >                double normalizedTime =
157 >                    (double) millisElapsedSince(startTime) / delay;
158 >                if (normalizedTime >= cycles - 1 &&
159 >                    normalizedTime <= cycles)
160 >                    return;
161 >            }
162 >            throw new AssertionError("unexpected execution rate");
163 >        } finally {
164 >            joinPool(p);
165 >        }
166      }
167  
168      /**
# Line 165 | Line 170 | public class ScheduledExecutorTest exten
170       */
171      public void testFixedDelaySequence() throws InterruptedException {
172          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
173 <        RunnableCounter counter = new RunnableCounter();
174 <        ScheduledFuture h =
175 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
176 <        delay(SMALL_DELAY_MS);
177 <        h.cancel(true);
178 <        int c = counter.count.get();
179 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
180 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
181 <        joinPool(p);
173 >        try {
174 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
175 >                long startTime = System.nanoTime();
176 >                int cycles = 10;
177 >                final CountDownLatch done = new CountDownLatch(cycles);
178 >                CheckedRunnable task = new CheckedRunnable() {
179 >                    public void realRun() { done.countDown(); }};
180 >                
181 >                ScheduledFuture h =
182 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
183 >                done.await();
184 >                h.cancel(true);
185 >                double normalizedTime =
186 >                    (double) millisElapsedSince(startTime) / delay;
187 >                if (normalizedTime >= cycles - 1 &&
188 >                    normalizedTime <= cycles)
189 >                    return;
190 >            }
191 >            throw new AssertionError("unexpected execution rate");
192 >        } finally {
193 >            joinPool(p);
194 >        }
195      }
196  
179
197      /**
198       * execute(null) throws NPE
199       */
# Line 327 | Line 344 | public class ScheduledExecutorTest exten
344                      threadProceed.await();
345                      threadDone.countDown();
346                  }});
347 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
347 >            await(threadStarted);
348              assertEquals(0, p.getCompletedTaskCount());
349              threadProceed.countDown();
350              threadDone.await();
351 <            delay(SHORT_DELAY_MS);
352 <            assertEquals(1, p.getCompletedTaskCount());
351 >            long startTime = System.nanoTime();
352 >            while (p.getCompletedTaskCount() != 1) {
353 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
354 >                    fail("timed out");
355 >                Thread.yield();
356 >            }
357          } finally {
358              joinPool(p);
359          }
# Line 459 | Line 480 | public class ScheduledExecutorTest exten
480      }
481  
482      /**
483 <     * isShutDown is false before shutdown, true after
483 >     * isShutdown is false before shutdown, true after
484       */
485      public void testIsShutdown() {
486  
# Line 473 | Line 494 | public class ScheduledExecutorTest exten
494          assertTrue(p.isShutdown());
495      }
496  
476
497      /**
498       * isTerminated is false before termination, true after
499       */
# Line 587 | Line 607 | public class ScheduledExecutorTest exten
607      }
608  
609      /**
610 <     * purge removes cancelled tasks from the queue
610 >     * purge eventually removes cancelled tasks from the queue
611       */
612      public void testPurge() throws InterruptedException {
613          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
614          ScheduledFuture[] tasks = new ScheduledFuture[5];
615 <        for (int i = 0; i < tasks.length; i++) {
616 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
617 <        }
615 >        for (int i = 0; i < tasks.length; i++)
616 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
617 >                                  LONG_DELAY_MS, MILLISECONDS);
618          try {
619              int max = tasks.length;
620              if (tasks[4].cancel(true)) --max;
621              if (tasks[3].cancel(true)) --max;
622              // There must eventually be an interference-free point at
623              // which purge will not fail. (At worst, when queue is empty.)
624 <            int k;
625 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
624 >            long startTime = System.nanoTime();
625 >            do {
626                  p.purge();
627                  long count = p.getTaskCount();
628 <                if (count >= 0 && count <= max)
629 <                    break;
630 <                delay(1);
631 <            }
612 <            assertTrue(k < SMALL_DELAY_MS);
628 >                if (count == max)
629 >                    return;
630 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
631 >            fail("Purge failed to remove cancelled tasks");
632          } finally {
633              for (ScheduledFuture task : tasks)
634                  task.cancel(true);
# Line 618 | Line 637 | public class ScheduledExecutorTest exten
637      }
638  
639      /**
640 <     * shutDownNow returns a list containing tasks that were not run
640 >     * shutdownNow returns a list containing tasks that were not run
641       */
642 <    public void testShutDownNow() throws InterruptedException {
642 >    public void testShutdownNow() {
643          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
644          for (int i = 0; i < 5; i++)
645 <            p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
646 <        List l;
645 >            p.schedule(new SmallPossiblyInterruptedRunnable(),
646 >                       LONG_DELAY_MS, MILLISECONDS);
647          try {
648 <            l = p.shutdownNow();
648 >            List<Runnable> l = p.shutdownNow();
649 >            assertTrue(p.isShutdown());
650 >            assertEquals(5, l.size());
651          } catch (SecurityException ok) {
652 <            return;
652 >            // Allowed in case test doesn't have privs
653 >        } finally {
654 >            joinPool(p);
655          }
633        assertTrue(p.isShutdown());
634        assertTrue(l.size() > 0 && l.size() <= 5);
635        joinPool(p);
656      }
657  
658      /**
659       * In default setting, shutdown cancels periodic but not delayed
660       * tasks at shutdown
661       */
662 <    public void testShutDown1() throws InterruptedException {
662 >    public void testShutdown1() throws InterruptedException {
663          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
664          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
665          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
# Line 664 | Line 684 | public class ScheduledExecutorTest exten
684          }
685      }
686  
667
687      /**
688       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
689       * delayed tasks are cancelled at shutdown
690       */
691 <    public void testShutDown2() throws InterruptedException {
691 >    public void testShutdown2() throws InterruptedException {
692          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
693          p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
694          assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 695 | Line 714 | public class ScheduledExecutorTest exten
714       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
715       * periodic tasks are cancelled at shutdown
716       */
717 <    public void testShutDown3() throws InterruptedException {
717 >    public void testShutdown3() throws InterruptedException {
718          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
719          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
720          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
721          p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
722          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
723          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
724 +        long initialDelay = LONG_DELAY_MS;
725          ScheduledFuture task =
726 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
726 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
727 >                                  5, MILLISECONDS);
728          try { p.shutdown(); } catch (SecurityException ok) { return; }
729          assertTrue(p.isShutdown());
709        BlockingQueue q = p.getQueue();
730          assertTrue(p.getQueue().isEmpty());
731          assertTrue(task.isDone());
732          assertTrue(task.isCancelled());
733 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
714 <        assertTrue(p.isTerminated());
733 >        joinPool(p);
734      }
735  
736      /**
737       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
738       * periodic tasks are not cancelled at shutdown
739       */
740 <    public void testShutDown4() throws InterruptedException {
740 >    public void testShutdown4() throws InterruptedException {
741          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
742          final CountDownLatch counter = new CountDownLatch(2);
743          try {
# Line 1160 | Line 1179 | public class ScheduledExecutorTest exten
1179              l.add(new StringTask());
1180              List<Future<String>> futures =
1181                  e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1182 <            assertEquals(3, futures.size());
1183 <            Iterator<Future<String>> it = futures.iterator();
1184 <            Future<String> f1 = it.next();
1185 <            Future<String> f2 = it.next();
1186 <            Future<String> f3 = it.next();
1168 <            assertTrue(f1.isDone());
1169 <            assertTrue(f2.isDone());
1170 <            assertTrue(f3.isDone());
1171 <            assertFalse(f1.isCancelled());
1172 <            assertTrue(f2.isCancelled());
1182 >            assertEquals(l.size(), futures.size());
1183 >            for (Future future : futures)
1184 >                assertTrue(future.isDone());
1185 >            assertFalse(futures.get(0).isCancelled());
1186 >            assertTrue(futures.get(1).isCancelled());
1187          } finally {
1188              joinPool(e);
1189          }
1190      }
1191  
1178
1192   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines