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.20 by jsr166, Thu Apr 14 22:55:08 2011 UTC vs.
Revision 1.37 by jsr166, Sun Sep 27 18:50:50 2015 UTC

# Line 4 | Line 4
4   * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7 import junit.framework.*;
8 import java.util.*;
9 import java.util.concurrent.*;
7   import static java.util.concurrent.TimeUnit.MILLISECONDS;
8 < import java.util.concurrent.atomic.*;
8 >
9 > import java.util.ArrayList;
10 > import java.util.List;
11 > import java.util.concurrent.BlockingQueue;
12 > import java.util.concurrent.Callable;
13 > import java.util.concurrent.CancellationException;
14 > import java.util.concurrent.CountDownLatch;
15 > import java.util.concurrent.Delayed;
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.RejectedExecutionHandler;
22 > import java.util.concurrent.RunnableScheduledFuture;
23 > import java.util.concurrent.ScheduledFuture;
24 > import java.util.concurrent.ScheduledThreadPoolExecutor;
25 > import java.util.concurrent.ThreadFactory;
26 > import java.util.concurrent.ThreadPoolExecutor;
27 > import java.util.concurrent.TimeoutException;
28 > import java.util.concurrent.TimeUnit;
29 > import java.util.concurrent.atomic.AtomicInteger;
30 >
31 > import junit.framework.Test;
32 > import junit.framework.TestSuite;
33  
34   public class ScheduledExecutorSubclassTest extends JSR166TestCase {
35      public static void main(String[] args) {
36 <        junit.textui.TestRunner.run(suite());
36 >        main(suite(), args);
37      }
38      public static Test suite() {
39          return new TestSuite(ScheduledExecutorSubclassTest.class);
# Line 36 | Line 57 | public class ScheduledExecutorSubclassTe
57          }
58          public boolean isCancelled() { return task.isCancelled(); }
59          public boolean isDone() { return task.isDone(); }
60 <        public V get() throws InterruptedException,  ExecutionException {
60 >        public V get() throws InterruptedException, ExecutionException {
61              V v = task.get();
62              assertTrue(ran);
63              return v;
64          }
65 <        public V get(long time, TimeUnit unit) throws InterruptedException,  ExecutionException, TimeoutException {
65 >        public V get(long time, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
66              V v = task.get(time, unit);
67              assertTrue(ran);
68              return v;
69          }
70      }
71  
51
72      public class CustomExecutor extends ScheduledThreadPoolExecutor {
73  
74          protected <V> RunnableScheduledFuture<V> decorateTask(Runnable r, RunnableScheduledFuture<V> task) {
# Line 58 | Line 78 | public class ScheduledExecutorSubclassTe
78          protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> c, RunnableScheduledFuture<V> task) {
79              return new CustomTask<V>(task);
80          }
81 <        CustomExecutor(int corePoolSize) { super(corePoolSize);}
81 >        CustomExecutor(int corePoolSize) { super(corePoolSize); }
82          CustomExecutor(int corePoolSize, RejectedExecutionHandler handler) {
83              super(corePoolSize, handler);
84          }
# Line 73 | Line 93 | public class ScheduledExecutorSubclassTe
93  
94      }
95  
76
96      /**
97       * execute successfully executes a runnable
98       */
# Line 92 | Line 111 | public class ScheduledExecutorSubclassTe
111          }
112      }
113  
95
114      /**
115       * delayed schedule of callable successfully executes after delay
116       */
117      public void testSchedule1() throws Exception {
118          CustomExecutor p = new CustomExecutor(1);
119 <        final long t0 = System.nanoTime();
102 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
119 >        final long startTime = System.nanoTime();
120          final CountDownLatch done = new CountDownLatch(1);
121          try {
122              Callable task = new CheckedCallable<Boolean>() {
123                  public Boolean realCall() {
124                      done.countDown();
125 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
125 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
126                      return Boolean.TRUE;
127                  }};
128 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
129 <            assertEquals(Boolean.TRUE, f.get());
130 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
128 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
129 >            assertSame(Boolean.TRUE, f.get());
130 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
131              assertTrue(done.await(0L, MILLISECONDS));
132          } finally {
133              joinPool(p);
# Line 122 | Line 139 | public class ScheduledExecutorSubclassTe
139       */
140      public void testSchedule3() throws Exception {
141          CustomExecutor p = new CustomExecutor(1);
142 <        final long t0 = System.nanoTime();
126 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
142 >        final long startTime = System.nanoTime();
143          final CountDownLatch done = new CountDownLatch(1);
144          try {
145              Runnable task = new CheckedRunnable() {
146                  public void realRun() {
147                      done.countDown();
148 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
148 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
149                  }};
150 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
151 <            assertNull(f.get());
152 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
153 <            assertTrue(done.await(0L, MILLISECONDS));
150 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
151 >            await(done);
152 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
153 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
154          } finally {
155              joinPool(p);
156          }
# Line 145 | Line 161 | public class ScheduledExecutorSubclassTe
161       */
162      public void testSchedule4() throws InterruptedException {
163          CustomExecutor p = new CustomExecutor(1);
164 <        final long t0 = System.nanoTime();
149 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
164 >        final long startTime = System.nanoTime();
165          final CountDownLatch done = new CountDownLatch(1);
166          try {
167              Runnable task = new CheckedRunnable() {
168                  public void realRun() {
169                      done.countDown();
170 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
170 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
171                  }};
172              ScheduledFuture f =
173 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
174 <                                      SHORT_DELAY_MS, MILLISECONDS);
175 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
176 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
173 >                p.scheduleAtFixedRate(task, timeoutMillis(),
174 >                                      LONG_DELAY_MS, MILLISECONDS);
175 >            await(done);
176 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
177              f.cancel(true);
178          } finally {
179              joinPool(p);
# Line 170 | Line 185 | public class ScheduledExecutorSubclassTe
185       */
186      public void testSchedule5() throws InterruptedException {
187          CustomExecutor p = new CustomExecutor(1);
188 <        final long t0 = System.nanoTime();
174 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
188 >        final long startTime = System.nanoTime();
189          final CountDownLatch done = new CountDownLatch(1);
190          try {
191              Runnable task = new CheckedRunnable() {
192                  public void realRun() {
193                      done.countDown();
194 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
194 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
195                  }};
196              ScheduledFuture f =
197 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
198 <                                         SHORT_DELAY_MS, MILLISECONDS);
199 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
200 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
197 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
198 >                                         LONG_DELAY_MS, MILLISECONDS);
199 >            await(done);
200 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
201              f.cancel(true);
202          } finally {
203              joinPool(p);
# Line 200 | Line 214 | public class ScheduledExecutorSubclassTe
214       */
215      public void testFixedRateSequence() throws InterruptedException {
216          CustomExecutor p = new CustomExecutor(1);
217 <        RunnableCounter counter = new RunnableCounter();
218 <        ScheduledFuture h =
219 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
220 <        Thread.sleep(SMALL_DELAY_MS);
221 <        h.cancel(true);
222 <        int c = counter.count.get();
223 <        // By time scaling conventions, we must have at least
224 <        // an execution per SHORT delay, but no more than one SHORT more
225 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
226 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
227 <        joinPool(p);
217 >        try {
218 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
219 >                long startTime = System.nanoTime();
220 >                int cycles = 10;
221 >                final CountDownLatch done = new CountDownLatch(cycles);
222 >                Runnable task = new CheckedRunnable() {
223 >                    public void realRun() { done.countDown(); }};
224 >                ScheduledFuture h =
225 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
226 >                done.await();
227 >                h.cancel(true);
228 >                double normalizedTime =
229 >                    (double) millisElapsedSince(startTime) / delay;
230 >                if (normalizedTime >= cycles - 1 &&
231 >                    normalizedTime <= cycles)
232 >                    return;
233 >            }
234 >            throw new AssertionError("unexpected execution rate");
235 >        } finally {
236 >            joinPool(p);
237 >        }
238      }
239  
240      /**
# Line 218 | Line 242 | public class ScheduledExecutorSubclassTe
242       */
243      public void testFixedDelaySequence() throws InterruptedException {
244          CustomExecutor p = new CustomExecutor(1);
245 <        RunnableCounter counter = new RunnableCounter();
246 <        ScheduledFuture h =
247 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
248 <        Thread.sleep(SMALL_DELAY_MS);
249 <        h.cancel(true);
250 <        int c = counter.count.get();
251 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
252 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
253 <        joinPool(p);
245 >        try {
246 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
247 >                long startTime = System.nanoTime();
248 >                int cycles = 10;
249 >                final CountDownLatch done = new CountDownLatch(cycles);
250 >                Runnable task = new CheckedRunnable() {
251 >                    public void realRun() { done.countDown(); }};
252 >                ScheduledFuture h =
253 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
254 >                done.await();
255 >                h.cancel(true);
256 >                double normalizedTime =
257 >                    (double) millisElapsedSince(startTime) / delay;
258 >                if (normalizedTime >= cycles - 1 &&
259 >                    normalizedTime <= cycles)
260 >                    return;
261 >            }
262 >            throw new AssertionError("unexpected execution rate");
263 >        } finally {
264 >            joinPool(p);
265 >        }
266      }
267  
232
268      /**
269       * execute(null) throws NPE
270       */
# Line 378 | Line 413 | public class ScheduledExecutorSubclassTe
413                      threadProceed.await();
414                      threadDone.countDown();
415                  }});
416 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
416 >            await(threadStarted);
417              assertEquals(0, p.getCompletedTaskCount());
418              threadProceed.countDown();
419              threadDone.await();
420 <            Thread.sleep(SHORT_DELAY_MS);
421 <            assertEquals(1, p.getCompletedTaskCount());
420 >            long startTime = System.nanoTime();
421 >            while (p.getCompletedTaskCount() != 1) {
422 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
423 >                    fail("timed out");
424 >                Thread.yield();
425 >            }
426          } finally {
427              joinPool(p);
428          }
# Line 510 | Line 549 | public class ScheduledExecutorSubclassTe
549      }
550  
551      /**
552 <     * isShutDown is false before shutdown, true after
552 >     * isShutdown is false before shutdown, true after
553       */
554      public void testIsShutdown() {
555          CustomExecutor p = new CustomExecutor(1);
# Line 523 | Line 562 | public class ScheduledExecutorSubclassTe
562          assertTrue(p.isShutdown());
563      }
564  
526
565      /**
566       * isTerminated is false before termination, true after
567       */
# Line 642 | Line 680 | public class ScheduledExecutorSubclassTe
680      public void testPurge() throws InterruptedException {
681          CustomExecutor p = new CustomExecutor(1);
682          ScheduledFuture[] tasks = new ScheduledFuture[5];
683 <        for (int i = 0; i < tasks.length; i++) {
684 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
685 <        }
683 >        for (int i = 0; i < tasks.length; i++)
684 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
685 >                                  LONG_DELAY_MS, MILLISECONDS);
686          try {
687              int max = tasks.length;
688              if (tasks[4].cancel(true)) --max;
689              if (tasks[3].cancel(true)) --max;
690              // There must eventually be an interference-free point at
691              // which purge will not fail. (At worst, when queue is empty.)
692 <            int k;
693 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
692 >            long startTime = System.nanoTime();
693 >            do {
694                  p.purge();
695                  long count = p.getTaskCount();
696 <                if (count >= 0 && count <= max)
697 <                    break;
698 <                Thread.sleep(1);
699 <            }
662 <            assertTrue(k < SMALL_DELAY_MS);
696 >                if (count == max)
697 >                    return;
698 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
699 >            fail("Purge failed to remove cancelled tasks");
700          } finally {
701              for (ScheduledFuture task : tasks)
702                  task.cancel(true);
# Line 668 | Line 705 | public class ScheduledExecutorSubclassTe
705      }
706  
707      /**
708 <     * shutDownNow returns a list containing tasks that were not run
708 >     * shutdownNow returns a list containing tasks that were not run,
709 >     * and those tasks are drained from the queue
710       */
711 <    public void testShutDownNow() {
711 >    public void testShutdownNow() {
712          CustomExecutor p = new CustomExecutor(1);
713          for (int i = 0; i < 5; i++)
714 <            p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
715 <        List l;
714 >            p.schedule(new SmallPossiblyInterruptedRunnable(),
715 >                       LONG_DELAY_MS, MILLISECONDS);
716          try {
717 <            l = p.shutdownNow();
717 >            List<Runnable> l = p.shutdownNow();
718 >            assertTrue(p.isShutdown());
719 >            assertTrue(p.getQueue().isEmpty());
720 >            assertEquals(5, l.size());
721          } catch (SecurityException ok) {
722 <            return;
722 >            // Allowed in case test doesn't have privs
723 >        } finally {
724 >            joinPool(p);
725          }
683        assertTrue(p.isShutdown());
684        assertTrue(l.size() > 0 && l.size() <= 5);
685        joinPool(p);
726      }
727  
728      /**
729       * In default setting, shutdown cancels periodic but not delayed
730       * tasks at shutdown
731       */
732 <    public void testShutDown1() throws InterruptedException {
732 >    public void testShutdown1() throws InterruptedException {
733          CustomExecutor p = new CustomExecutor(1);
734          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
735          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
# Line 714 | Line 754 | public class ScheduledExecutorSubclassTe
754          }
755      }
756  
717
757      /**
758       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
759       * delayed tasks are cancelled at shutdown
760       */
761 <    public void testShutDown2() throws InterruptedException {
761 >    public void testShutdown2() throws InterruptedException {
762          CustomExecutor p = new CustomExecutor(1);
763          p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
764          assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 741 | Line 780 | public class ScheduledExecutorSubclassTe
780          }
781      }
782  
744
783      /**
784       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
785       * periodic tasks are cancelled at shutdown
786       */
787 <    public void testShutDown3() throws InterruptedException {
787 >    public void testShutdown3() throws InterruptedException {
788          CustomExecutor p = new CustomExecutor(1);
789          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
790          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
791          p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
792          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
793          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
794 +        long initialDelay = LONG_DELAY_MS;
795          ScheduledFuture task =
796 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
796 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
797 >                                  5, MILLISECONDS);
798          try { p.shutdown(); } catch (SecurityException ok) { return; }
799          assertTrue(p.isShutdown());
760        BlockingQueue q = p.getQueue();
800          assertTrue(p.getQueue().isEmpty());
801          assertTrue(task.isDone());
802          assertTrue(task.isCancelled());
803 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
765 <        assertTrue(p.isTerminated());
803 >        joinPool(p);
804      }
805  
806      /**
807       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
808       * periodic tasks are not cancelled at shutdown
809       */
810 <    public void testShutDown4() throws InterruptedException {
810 >    public void testShutdown4() throws InterruptedException {
811          CustomExecutor p = new CustomExecutor(1);
812          final CountDownLatch counter = new CountDownLatch(2);
813          try {
# Line 1205 | Line 1243 | public class ScheduledExecutorSubclassTe
1243      public void testTimedInvokeAll6() throws Exception {
1244          ExecutorService e = new CustomExecutor(2);
1245          try {
1246 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1247 <            l.add(new StringTask());
1248 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1249 <            l.add(new StringTask());
1250 <            List<Future<String>> futures =
1251 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1252 <            assertEquals(3, futures.size());
1253 <            Iterator<Future<String>> it = futures.iterator();
1254 <            Future<String> f1 = it.next();
1255 <            Future<String> f2 = it.next();
1256 <            Future<String> f3 = it.next();
1257 <            assertTrue(f1.isDone());
1258 <            assertTrue(f2.isDone());
1259 <            assertTrue(f3.isDone());
1260 <            assertFalse(f1.isCancelled());
1261 <            assertTrue(f2.isCancelled());
1246 >            for (long timeout = timeoutMillis();;) {
1247 >                List<Callable<String>> tasks = new ArrayList<>();
1248 >                tasks.add(new StringTask("0"));
1249 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1250 >                tasks.add(new StringTask("2"));
1251 >                long startTime = System.nanoTime();
1252 >                List<Future<String>> futures =
1253 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1254 >                assertEquals(tasks.size(), futures.size());
1255 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1256 >                for (Future future : futures)
1257 >                    assertTrue(future.isDone());
1258 >                assertTrue(futures.get(1).isCancelled());
1259 >                try {
1260 >                    assertEquals("0", futures.get(0).get());
1261 >                    assertEquals("2", futures.get(2).get());
1262 >                    break;
1263 >                } catch (CancellationException retryWithLongerTimeout) {
1264 >                    timeout *= 2;
1265 >                    if (timeout >= LONG_DELAY_MS / 2)
1266 >                        fail("expected exactly one task to be cancelled");
1267 >                }
1268 >            }
1269          } finally {
1270              joinPool(e);
1271          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines