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.40 by jsr166, Sat May 7 19:34:51 2011 UTC vs.
Revision 1.50 by jsr166, Wed Dec 31 19:05:43 2014 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.concurrent.atomic.*;
10 >
11 > import java.util.ArrayList;
12 > import java.util.List;
13 > import java.util.concurrent.BlockingQueue;
14 > import java.util.concurrent.Callable;
15 > import java.util.concurrent.CountDownLatch;
16 > import java.util.concurrent.ExecutionException;
17 > import java.util.concurrent.Executors;
18 > import java.util.concurrent.ExecutorService;
19 > import java.util.concurrent.Future;
20 > import java.util.concurrent.RejectedExecutionException;
21 > import java.util.concurrent.ScheduledFuture;
22 > import java.util.concurrent.ScheduledThreadPoolExecutor;
23 > import java.util.concurrent.ThreadFactory;
24 > import java.util.concurrent.ThreadPoolExecutor;
25 > import java.util.concurrent.atomic.AtomicInteger;
26 >
27 > import junit.framework.Test;
28 > import junit.framework.TestSuite;
29  
30   public class ScheduledExecutorTest extends JSR166TestCase {
31      public static void main(String[] args) {
# Line 20 | Line 35 | public class ScheduledExecutorTest exten
35          return new TestSuite(ScheduledExecutorTest.class);
36      }
37  
23
38      /**
39       * execute successfully executes a runnable
40       */
# Line 39 | Line 53 | public class ScheduledExecutorTest exten
53          }
54      }
55  
42
56      /**
57       * delayed schedule of callable successfully executes after delay
58       */
59      public void testSchedule1() throws Exception {
60          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
61 <        final long t0 = System.nanoTime();
49 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
61 >        final long startTime = System.nanoTime();
62          final CountDownLatch done = new CountDownLatch(1);
63          try {
64              Callable task = new CheckedCallable<Boolean>() {
65                  public Boolean realCall() {
66                      done.countDown();
67 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
67 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
68                      return Boolean.TRUE;
69                  }};
70 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
71 <            assertEquals(Boolean.TRUE, f.get());
72 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
70 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
71 >            assertSame(Boolean.TRUE, f.get());
72 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
73              assertTrue(done.await(0L, MILLISECONDS));
74          } finally {
75              joinPool(p);
# Line 69 | Line 81 | public class ScheduledExecutorTest exten
81       */
82      public void testSchedule3() throws Exception {
83          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
84 <        final long t0 = System.nanoTime();
73 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
84 >        final long startTime = System.nanoTime();
85          final CountDownLatch done = new CountDownLatch(1);
86          try {
87              Runnable task = new CheckedRunnable() {
88                  public void realRun() {
89                      done.countDown();
90 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
90 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
91                  }};
92 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
93 <            assertNull(f.get());
94 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
95 <            assertTrue(done.await(0L, MILLISECONDS));
92 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
93 >            await(done);
94 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
95 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
96          } finally {
97              joinPool(p);
98          }
# Line 92 | Line 103 | public class ScheduledExecutorTest exten
103       */
104      public void testSchedule4() throws Exception {
105          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
106 <        final long t0 = System.nanoTime();
96 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
106 >        final long startTime = System.nanoTime();
107          final CountDownLatch done = new CountDownLatch(1);
108          try {
109              Runnable task = new CheckedRunnable() {
110                  public void realRun() {
111                      done.countDown();
112 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
112 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
113                  }};
114              ScheduledFuture f =
115 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
116 <                                      SHORT_DELAY_MS, MILLISECONDS);
117 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
118 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
115 >                p.scheduleAtFixedRate(task, timeoutMillis(),
116 >                                      LONG_DELAY_MS, MILLISECONDS);
117 >            await(done);
118 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
119              f.cancel(true);
120          } finally {
121              joinPool(p);
# Line 115 | Line 125 | public class ScheduledExecutorTest exten
125      /**
126       * scheduleWithFixedDelay executes runnable after given initial delay
127       */
128 <    public void testSchedule5() throws InterruptedException {
128 >    public void testSchedule5() throws Exception {
129          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
130 <        final long t0 = System.nanoTime();
121 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
130 >        final long startTime = System.nanoTime();
131          final CountDownLatch done = new CountDownLatch(1);
132          try {
133              Runnable task = new CheckedRunnable() {
134                  public void realRun() {
135                      done.countDown();
136 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
136 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
137                  }};
138              ScheduledFuture f =
139 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
140 <                                         SHORT_DELAY_MS, MILLISECONDS);
141 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
142 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
139 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
140 >                                         LONG_DELAY_MS, MILLISECONDS);
141 >            await(done);
142 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
143              f.cancel(true);
144          } finally {
145              joinPool(p);
# Line 147 | Line 156 | public class ScheduledExecutorTest exten
156       */
157      public void testFixedRateSequence() throws InterruptedException {
158          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
159 <        RunnableCounter counter = new RunnableCounter();
160 <        ScheduledFuture h =
161 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
162 <        delay(SMALL_DELAY_MS);
163 <        h.cancel(true);
164 <        int c = counter.count.get();
165 <        // By time scaling conventions, we must have at least
166 <        // an execution per SHORT delay, but no more than one SHORT more
167 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
168 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
169 <        joinPool(p);
159 >        try {
160 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
161 >                long startTime = System.nanoTime();
162 >                int cycles = 10;
163 >                final CountDownLatch done = new CountDownLatch(cycles);
164 >                Runnable task = new CheckedRunnable() {
165 >                    public void realRun() { done.countDown(); }};
166 >                ScheduledFuture h =
167 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
168 >                done.await();
169 >                h.cancel(true);
170 >                double normalizedTime =
171 >                    (double) millisElapsedSince(startTime) / delay;
172 >                if (normalizedTime >= cycles - 1 &&
173 >                    normalizedTime <= cycles)
174 >                    return;
175 >            }
176 >            throw new AssertionError("unexpected execution rate");
177 >        } finally {
178 >            joinPool(p);
179 >        }
180      }
181  
182      /**
# Line 165 | Line 184 | public class ScheduledExecutorTest exten
184       */
185      public void testFixedDelaySequence() throws InterruptedException {
186          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
187 <        RunnableCounter counter = new RunnableCounter();
188 <        ScheduledFuture h =
189 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
190 <        delay(SMALL_DELAY_MS);
191 <        h.cancel(true);
192 <        int c = counter.count.get();
193 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
194 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
195 <        joinPool(p);
187 >        try {
188 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
189 >                long startTime = System.nanoTime();
190 >                int cycles = 10;
191 >                final CountDownLatch done = new CountDownLatch(cycles);
192 >                Runnable task = new CheckedRunnable() {
193 >                    public void realRun() { done.countDown(); }};
194 >                ScheduledFuture h =
195 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
196 >                done.await();
197 >                h.cancel(true);
198 >                double normalizedTime =
199 >                    (double) millisElapsedSince(startTime) / delay;
200 >                if (normalizedTime >= cycles - 1 &&
201 >                    normalizedTime <= cycles)
202 >                    return;
203 >            }
204 >            throw new AssertionError("unexpected execution rate");
205 >        } finally {
206 >            joinPool(p);
207 >        }
208      }
209  
179
210      /**
211       * execute(null) throws NPE
212       */
# Line 327 | Line 357 | public class ScheduledExecutorTest exten
357                      threadProceed.await();
358                      threadDone.countDown();
359                  }});
360 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
360 >            await(threadStarted);
361              assertEquals(0, p.getCompletedTaskCount());
362              threadProceed.countDown();
363              threadDone.await();
364 <            delay(SHORT_DELAY_MS);
365 <            assertEquals(1, p.getCompletedTaskCount());
364 >            long startTime = System.nanoTime();
365 >            while (p.getCompletedTaskCount() != 1) {
366 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
367 >                    fail("timed out");
368 >                Thread.yield();
369 >            }
370          } finally {
371              joinPool(p);
372          }
# Line 459 | Line 493 | public class ScheduledExecutorTest exten
493      }
494  
495      /**
496 <     * isShutDown is false before shutdown, true after
496 >     * isShutdown is false before shutdown, true after
497       */
498      public void testIsShutdown() {
499  
# Line 473 | Line 507 | public class ScheduledExecutorTest exten
507          assertTrue(p.isShutdown());
508      }
509  
476
510      /**
511       * isTerminated is false before termination, true after
512       */
# Line 617 | Line 650 | public class ScheduledExecutorTest exten
650      }
651  
652      /**
653 <     * shutDownNow returns a list containing tasks that were not run
653 >     * shutdownNow returns a list containing tasks that were not run
654       */
655      public void testShutdownNow() {
656          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
# Line 639 | Line 672 | public class ScheduledExecutorTest exten
672       * In default setting, shutdown cancels periodic but not delayed
673       * tasks at shutdown
674       */
675 <    public void testShutDown1() throws InterruptedException {
675 >    public void testShutdown1() throws InterruptedException {
676          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
677          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
678          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
# Line 664 | Line 697 | public class ScheduledExecutorTest exten
697          }
698      }
699  
667
700      /**
701       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
702       * delayed tasks are cancelled at shutdown
703       */
704 <    public void testShutDown2() throws InterruptedException {
704 >    public void testShutdown2() throws InterruptedException {
705          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
706          p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
707          assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 695 | Line 727 | public class ScheduledExecutorTest exten
727       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
728       * periodic tasks are cancelled at shutdown
729       */
730 <    public void testShutDown3() throws InterruptedException {
730 >    public void testShutdown3() throws InterruptedException {
731          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
732          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
733          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
734          p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
735          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
736          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
737 +        long initialDelay = LONG_DELAY_MS;
738          ScheduledFuture task =
739 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
739 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
740 >                                  5, MILLISECONDS);
741          try { p.shutdown(); } catch (SecurityException ok) { return; }
742          assertTrue(p.isShutdown());
709        BlockingQueue q = p.getQueue();
743          assertTrue(p.getQueue().isEmpty());
744          assertTrue(task.isDone());
745          assertTrue(task.isCancelled());
746 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
714 <        assertTrue(p.isTerminated());
746 >        joinPool(p);
747      }
748  
749      /**
750       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
751       * periodic tasks are not cancelled at shutdown
752       */
753 <    public void testShutDown4() throws InterruptedException {
753 >    public void testShutdown4() throws InterruptedException {
754          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
755          final CountDownLatch counter = new CountDownLatch(2);
756          try {
# Line 1160 | Line 1192 | public class ScheduledExecutorTest exten
1192              l.add(new StringTask());
1193              List<Future<String>> futures =
1194                  e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1195 <            assertEquals(3, futures.size());
1196 <            Iterator<Future<String>> it = futures.iterator();
1197 <            Future<String> f1 = it.next();
1198 <            Future<String> f2 = it.next();
1199 <            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());
1195 >            assertEquals(l.size(), futures.size());
1196 >            for (Future future : futures)
1197 >                assertTrue(future.isDone());
1198 >            assertFalse(futures.get(0).isCancelled());
1199 >            assertTrue(futures.get(1).isCancelled());
1200          } finally {
1201              joinPool(e);
1202          }
1203      }
1204  
1178
1205   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines