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.35 by jsr166, Wed Nov 17 23:12:31 2010 UTC vs.
Revision 1.54 by jsr166, Sun Sep 27 20:17:39 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
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 > import static java.util.concurrent.TimeUnit.SECONDS;
11 >
12 > import java.util.ArrayList;
13 > import java.util.HashSet;
14 > import java.util.List;
15 > import java.util.concurrent.BlockingQueue;
16 > import java.util.concurrent.Callable;
17 > import java.util.concurrent.CancellationException;
18 > import java.util.concurrent.CountDownLatch;
19 > 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;
24 > import java.util.concurrent.ScheduledFuture;
25 > import java.util.concurrent.ScheduledThreadPoolExecutor;
26 > import java.util.concurrent.ThreadFactory;
27 > import java.util.concurrent.ThreadPoolExecutor;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 >
30 > import junit.framework.Test;
31 > import junit.framework.TestSuite;
32  
33   public class ScheduledExecutorTest extends JSR166TestCase {
34      public static void main(String[] args) {
35 <        junit.textui.TestRunner.run(suite());
35 >        main(suite(), args);
36      }
37      public static Test suite() {
38          return new TestSuite(ScheduledExecutorTest.class);
39      }
40  
23
41      /**
42       * execute successfully executes a runnable
43       */
# Line 39 | Line 56 | public class ScheduledExecutorTest exten
56          }
57      }
58  
42
59      /**
60       * delayed schedule of callable successfully executes after delay
61       */
62      public void testSchedule1() throws Exception {
63          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
64 <        final long t0 = System.nanoTime();
49 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
64 >        final long startTime = System.nanoTime();
65          final CountDownLatch done = new CountDownLatch(1);
66          try {
67              Callable task = new CheckedCallable<Boolean>() {
68                  public Boolean realCall() {
69                      done.countDown();
70 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
70 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
71                      return Boolean.TRUE;
72                  }};
73 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
74 <            assertEquals(Boolean.TRUE, f.get());
75 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
73 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
74 >            assertSame(Boolean.TRUE, f.get());
75 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76              assertTrue(done.await(0L, MILLISECONDS));
77          } finally {
78              joinPool(p);
# Line 69 | Line 84 | public class ScheduledExecutorTest exten
84       */
85      public void testSchedule3() throws Exception {
86          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
87 <        final long t0 = System.nanoTime();
73 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
87 >        final long startTime = System.nanoTime();
88          final CountDownLatch done = new CountDownLatch(1);
89          try {
90              Runnable task = new CheckedRunnable() {
91                  public void realRun() {
92                      done.countDown();
93 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
93 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
94                  }};
95 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
96 <            assertNull(f.get());
97 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
98 <            assertTrue(done.await(0L, MILLISECONDS));
95 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
96 >            await(done);
97 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
98 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
99          } finally {
100              joinPool(p);
101          }
# Line 92 | Line 106 | public class ScheduledExecutorTest exten
106       */
107      public void testSchedule4() throws Exception {
108          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
109 <        final long t0 = System.nanoTime();
96 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
109 >        final long startTime = System.nanoTime();
110          final CountDownLatch done = new CountDownLatch(1);
111          try {
112              Runnable task = new CheckedRunnable() {
113                  public void realRun() {
114                      done.countDown();
115 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
115 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
116                  }};
117              ScheduledFuture f =
118 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
119 <                                      SHORT_DELAY_MS, MILLISECONDS);
120 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
121 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
118 >                p.scheduleAtFixedRate(task, timeoutMillis(),
119 >                                      LONG_DELAY_MS, MILLISECONDS);
120 >            await(done);
121 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
122              f.cancel(true);
123          } finally {
124              joinPool(p);
# Line 115 | Line 128 | public class ScheduledExecutorTest exten
128      /**
129       * scheduleWithFixedDelay executes runnable after given initial delay
130       */
131 <    public void testSchedule5() throws InterruptedException {
131 >    public void testSchedule5() throws Exception {
132          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
133 <        final long t0 = System.nanoTime();
121 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
133 >        final long startTime = System.nanoTime();
134          final CountDownLatch done = new CountDownLatch(1);
135          try {
136              Runnable task = new CheckedRunnable() {
137                  public void realRun() {
138                      done.countDown();
139 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
139 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
140                  }};
141              ScheduledFuture f =
142 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
143 <                                         SHORT_DELAY_MS, MILLISECONDS);
144 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
145 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
142 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
143 >                                         LONG_DELAY_MS, MILLISECONDS);
144 >            await(done);
145 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
146              f.cancel(true);
147          } finally {
148              joinPool(p);
# Line 147 | Line 159 | public class ScheduledExecutorTest exten
159       */
160      public void testFixedRateSequence() throws InterruptedException {
161          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
162 <        RunnableCounter counter = new RunnableCounter();
163 <        ScheduledFuture h =
164 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
165 <        Thread.sleep(SMALL_DELAY_MS);
166 <        h.cancel(true);
167 <        int c = counter.count.get();
168 <        // By time scaling conventions, we must have at least
169 <        // an execution per SHORT delay, but no more than one SHORT more
170 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
171 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
172 <        joinPool(p);
162 >        try {
163 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
164 >                long startTime = System.nanoTime();
165 >                int cycles = 10;
166 >                final CountDownLatch done = new CountDownLatch(cycles);
167 >                Runnable task = new CheckedRunnable() {
168 >                    public void realRun() { done.countDown(); }};
169 >                ScheduledFuture h =
170 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
171 >                done.await();
172 >                h.cancel(true);
173 >                double normalizedTime =
174 >                    (double) millisElapsedSince(startTime) / delay;
175 >                if (normalizedTime >= cycles - 1 &&
176 >                    normalizedTime <= cycles)
177 >                    return;
178 >            }
179 >            throw new AssertionError("unexpected execution rate");
180 >        } finally {
181 >            joinPool(p);
182 >        }
183      }
184  
185      /**
# Line 165 | Line 187 | public class ScheduledExecutorTest exten
187       */
188      public void testFixedDelaySequence() throws InterruptedException {
189          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
190 <        RunnableCounter counter = new RunnableCounter();
191 <        ScheduledFuture h =
192 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
193 <        Thread.sleep(SMALL_DELAY_MS);
194 <        h.cancel(true);
195 <        int c = counter.count.get();
196 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
197 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
198 <        joinPool(p);
190 >        try {
191 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
192 >                long startTime = System.nanoTime();
193 >                int cycles = 10;
194 >                final CountDownLatch done = new CountDownLatch(cycles);
195 >                Runnable task = new CheckedRunnable() {
196 >                    public void realRun() { done.countDown(); }};
197 >                ScheduledFuture h =
198 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
199 >                done.await();
200 >                h.cancel(true);
201 >                double normalizedTime =
202 >                    (double) millisElapsedSince(startTime) / delay;
203 >                if (normalizedTime >= cycles - 1 &&
204 >                    normalizedTime <= cycles)
205 >                    return;
206 >            }
207 >            throw new AssertionError("unexpected execution rate");
208 >        } finally {
209 >            joinPool(p);
210 >        }
211      }
212  
179
213      /**
214       * execute(null) throws NPE
215       */
# Line 240 | Line 273 | public class ScheduledExecutorTest exten
273      /**
274       * schedule callable throws RejectedExecutionException if shutdown
275       */
276 <     public void testSchedule3_RejectedExecutionException() throws InterruptedException {
277 <         ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
278 <         try {
276 >    public void testSchedule3_RejectedExecutionException() throws InterruptedException {
277 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
278 >        try {
279              se.shutdown();
280              se.schedule(new NoOpCallable(),
281                          MEDIUM_DELAY_MS, MILLISECONDS);
# Line 250 | Line 283 | public class ScheduledExecutorTest exten
283          } catch (RejectedExecutionException success) {
284          } catch (SecurityException ok) {
285          }
286 <         joinPool(se);
286 >        joinPool(se);
287      }
288  
289      /**
# Line 327 | Line 360 | public class ScheduledExecutorTest exten
360                      threadProceed.await();
361                      threadDone.countDown();
362                  }});
363 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
363 >            await(threadStarted);
364              assertEquals(0, p.getCompletedTaskCount());
365              threadProceed.countDown();
366              threadDone.await();
367 <            Thread.sleep(SHORT_DELAY_MS);
368 <            assertEquals(1, p.getCompletedTaskCount());
367 >            long startTime = System.nanoTime();
368 >            while (p.getCompletedTaskCount() != 1) {
369 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
370 >                    fail("timed out");
371 >                Thread.yield();
372 >            }
373          } finally {
374              joinPool(p);
375          }
# Line 459 | Line 496 | public class ScheduledExecutorTest exten
496      }
497  
498      /**
499 <     * isShutDown is false before shutdown, true after
499 >     * isShutdown is false before shutdown, true after
500       */
501      public void testIsShutdown() {
502  
# Line 473 | Line 510 | public class ScheduledExecutorTest exten
510          assertTrue(p.isShutdown());
511      }
512  
476
513      /**
514       * isTerminated is false before termination, true after
515       */
# Line 485 | Line 521 | public class ScheduledExecutorTest exten
521          try {
522              p.execute(new CheckedRunnable() {
523                  public void realRun() throws InterruptedException {
488                    threadStarted.countDown();
524                      assertFalse(p.isTerminated());
525 +                    threadStarted.countDown();
526                      done.await();
527                  }});
528              assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
529 +            assertFalse(p.isTerminating());
530              done.countDown();
531          } finally {
532              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 586 | Line 623 | public class ScheduledExecutorTest exten
623      }
624  
625      /**
626 <     * purge removes cancelled tasks from the queue
626 >     * purge eventually removes cancelled tasks from the queue
627       */
628      public void testPurge() throws InterruptedException {
629          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
630          ScheduledFuture[] tasks = new ScheduledFuture[5];
631 <        for (int i = 0; i < tasks.length; i++) {
632 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
633 <        }
631 >        for (int i = 0; i < tasks.length; i++)
632 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
633 >                                  LONG_DELAY_MS, MILLISECONDS);
634          try {
635              int max = tasks.length;
636              if (tasks[4].cancel(true)) --max;
637              if (tasks[3].cancel(true)) --max;
638              // There must eventually be an interference-free point at
639              // which purge will not fail. (At worst, when queue is empty.)
640 <            int k;
641 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
640 >            long startTime = System.nanoTime();
641 >            do {
642                  p.purge();
643                  long count = p.getTaskCount();
644 <                if (count >= 0 && count <= max)
645 <                    break;
646 <                Thread.sleep(1);
647 <            }
611 <            assertTrue(k < SMALL_DELAY_MS);
644 >                if (count == max)
645 >                    return;
646 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
647 >            fail("Purge failed to remove cancelled tasks");
648          } finally {
649              for (ScheduledFuture task : tasks)
650                  task.cancel(true);
# Line 617 | Line 653 | public class ScheduledExecutorTest exten
653      }
654  
655      /**
656 <     * shutDownNow returns a list containing tasks that were not run
656 >     * shutdownNow returns a list containing tasks that were not run,
657 >     * and those tasks are drained from the queue
658       */
659 <    public void testShutDownNow() throws InterruptedException {
659 >    public void testShutdownNow_delayedTasks() throws InterruptedException {
660          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
661 <        for (int i = 0; i < 5; i++)
662 <            p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
663 <        List l;
661 >        List<ScheduledFuture> tasks = new ArrayList<>();
662 >        for (int i = 0; i < 3; i++) {
663 >            Runnable r = new NoOpRunnable();
664 >            tasks.add(p.schedule(r, 9, SECONDS));
665 >            tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
666 >            tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
667 >        }
668 >        assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
669 >        final List<Runnable> queuedTasks;
670          try {
671 <            l = p.shutdownNow();
671 >            queuedTasks = p.shutdownNow();
672          } catch (SecurityException ok) {
673 <            return;
673 >            return; // Allowed in case test doesn't have privs
674          }
675          assertTrue(p.isShutdown());
676 <        assertTrue(l.size() > 0 && l.size() <= 5);
677 <        joinPool(p);
676 >        assertTrue(p.getQueue().isEmpty());
677 >        assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
678 >        assertEquals(tasks.size(), queuedTasks.size());
679 >        for (ScheduledFuture task : tasks) {
680 >            assertFalse(task.isDone());
681 >            assertFalse(task.isCancelled());
682 >        }
683 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
684 >        assertTrue(p.isTerminated());
685      }
686  
687      /**
688       * In default setting, shutdown cancels periodic but not delayed
689       * tasks at shutdown
690       */
691 <    public void testShutDown1() throws InterruptedException {
691 >    public void testShutdown1() throws InterruptedException {
692          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
693          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
694          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
# Line 663 | Line 713 | public class ScheduledExecutorTest exten
713          }
714      }
715  
666
716      /**
717       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
718       * delayed tasks are cancelled at shutdown
719       */
720 <    public void testShutDown2() throws InterruptedException {
720 >    public void testShutdown2() throws InterruptedException {
721          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
722          p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
723          assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 694 | Line 743 | public class ScheduledExecutorTest exten
743       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
744       * periodic tasks are cancelled at shutdown
745       */
746 <    public void testShutDown3() throws InterruptedException {
746 >    public void testShutdown3() throws InterruptedException {
747          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
748          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
749          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
750          p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
751          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
752          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
753 +        long initialDelay = LONG_DELAY_MS;
754          ScheduledFuture task =
755 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
755 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
756 >                                  5, MILLISECONDS);
757          try { p.shutdown(); } catch (SecurityException ok) { return; }
758          assertTrue(p.isShutdown());
708        BlockingQueue q = p.getQueue();
759          assertTrue(p.getQueue().isEmpty());
760          assertTrue(task.isDone());
761          assertTrue(task.isCancelled());
762 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
713 <        assertTrue(p.isTerminated());
762 >        joinPool(p);
763      }
764  
765      /**
766       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
767       * periodic tasks are not cancelled at shutdown
768       */
769 <    public void testShutDown4() throws InterruptedException {
769 >    public void testShutdown4() throws InterruptedException {
770          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
771          final CountDownLatch counter = new CountDownLatch(2);
772          try {
# Line 1153 | Line 1202 | public class ScheduledExecutorTest exten
1202      public void testTimedInvokeAll6() throws Exception {
1203          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1204          try {
1205 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1206 <            l.add(new StringTask());
1207 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1208 <            l.add(new StringTask());
1209 <            List<Future<String>> futures =
1210 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1211 <            assertEquals(3, futures.size());
1212 <            Iterator<Future<String>> it = futures.iterator();
1213 <            Future<String> f1 = it.next();
1214 <            Future<String> f2 = it.next();
1215 <            Future<String> f3 = it.next();
1216 <            assertTrue(f1.isDone());
1217 <            assertTrue(f2.isDone());
1218 <            assertTrue(f3.isDone());
1219 <            assertFalse(f1.isCancelled());
1220 <            assertTrue(f2.isCancelled());
1205 >            for (long timeout = timeoutMillis();;) {
1206 >                List<Callable<String>> tasks = new ArrayList<>();
1207 >                tasks.add(new StringTask("0"));
1208 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1209 >                tasks.add(new StringTask("2"));
1210 >                long startTime = System.nanoTime();
1211 >                List<Future<String>> futures =
1212 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1213 >                assertEquals(tasks.size(), futures.size());
1214 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1215 >                for (Future future : futures)
1216 >                    assertTrue(future.isDone());
1217 >                assertTrue(futures.get(1).isCancelled());
1218 >                try {
1219 >                    assertEquals("0", futures.get(0).get());
1220 >                    assertEquals("2", futures.get(2).get());
1221 >                    break;
1222 >                } catch (CancellationException retryWithLongerTimeout) {
1223 >                    timeout *= 2;
1224 >                    if (timeout >= LONG_DELAY_MS / 2)
1225 >                        fail("expected exactly one task to be cancelled");
1226 >                }
1227 >            }
1228          } finally {
1229              joinPool(e);
1230          }
1231      }
1232  
1177
1233   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines