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.19 by jsr166, Tue Mar 15 19:47:07 2011 UTC vs.
Revision 1.31 by jsr166, Tue Sep 24 18:35:21 2013 UTC

# Line 8 | Line 8 | import junit.framework.*;
8   import java.util.*;
9   import java.util.concurrent.*;
10   import static java.util.concurrent.TimeUnit.MILLISECONDS;
11 < import java.util.concurrent.atomic.*;
11 > import java.util.concurrent.atomic.AtomicInteger;
12  
13   public class ScheduledExecutorSubclassTest extends JSR166TestCase {
14      public static void main(String[] args) {
# Line 36 | Line 36 | public class ScheduledExecutorSubclassTe
36          }
37          public boolean isCancelled() { return task.isCancelled(); }
38          public boolean isDone() { return task.isDone(); }
39 <        public V get() throws InterruptedException,  ExecutionException {
39 >        public V get() throws InterruptedException, ExecutionException {
40              V v = task.get();
41              assertTrue(ran);
42              return v;
43          }
44 <        public V get(long time, TimeUnit unit) throws InterruptedException,  ExecutionException, TimeoutException {
44 >        public V get(long time, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
45              V v = task.get(time, unit);
46              assertTrue(ran);
47              return v;
48          }
49      }
50  
51
51      public class CustomExecutor extends ScheduledThreadPoolExecutor {
52  
53          protected <V> RunnableScheduledFuture<V> decorateTask(Runnable r, RunnableScheduledFuture<V> task) {
# Line 58 | Line 57 | public class ScheduledExecutorSubclassTe
57          protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> c, RunnableScheduledFuture<V> task) {
58              return new CustomTask<V>(task);
59          }
60 <        CustomExecutor(int corePoolSize) { super(corePoolSize);}
60 >        CustomExecutor(int corePoolSize) { super(corePoolSize); }
61          CustomExecutor(int corePoolSize, RejectedExecutionHandler handler) {
62              super(corePoolSize, handler);
63          }
# Line 73 | Line 72 | public class ScheduledExecutorSubclassTe
72  
73      }
74  
76
75      /**
76       * execute successfully executes a runnable
77       */
# Line 92 | Line 90 | public class ScheduledExecutorSubclassTe
90          }
91      }
92  
95
93      /**
94       * delayed schedule of callable successfully executes after delay
95       */
96      public void testSchedule1() throws Exception {
97          CustomExecutor p = new CustomExecutor(1);
98 <        final long t0 = System.nanoTime();
102 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
98 >        final long startTime = System.nanoTime();
99          final CountDownLatch done = new CountDownLatch(1);
100          try {
101              Callable task = new CheckedCallable<Boolean>() {
102                  public Boolean realCall() {
103                      done.countDown();
104 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
104 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
105                      return Boolean.TRUE;
106                  }};
107 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
108 <            assertEquals(Boolean.TRUE, f.get());
109 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
107 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
108 >            assertSame(Boolean.TRUE, f.get());
109 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
110              assertTrue(done.await(0L, MILLISECONDS));
111          } finally {
112              joinPool(p);
# Line 122 | Line 118 | public class ScheduledExecutorSubclassTe
118       */
119      public void testSchedule3() throws Exception {
120          CustomExecutor p = new CustomExecutor(1);
121 <        final long t0 = System.nanoTime();
126 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
121 >        final long startTime = System.nanoTime();
122          final CountDownLatch done = new CountDownLatch(1);
123          try {
124              Runnable task = new CheckedRunnable() {
125                  public void realRun() {
126                      done.countDown();
127 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
127 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
128                  }};
129 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
130 <            assertNull(f.get());
131 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
132 <            assertTrue(done.await(0L, MILLISECONDS));
129 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
130 >            await(done);
131 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
132 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
133          } finally {
134              joinPool(p);
135          }
# Line 145 | Line 140 | public class ScheduledExecutorSubclassTe
140       */
141      public void testSchedule4() throws InterruptedException {
142          CustomExecutor p = new CustomExecutor(1);
143 <        final long t0 = System.nanoTime();
149 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
143 >        final long startTime = System.nanoTime();
144          final CountDownLatch done = new CountDownLatch(1);
145          try {
146              Runnable task = new CheckedRunnable() {
147                  public void realRun() {
148                      done.countDown();
149 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
149 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
150                  }};
151              ScheduledFuture f =
152 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
153 <                                      SHORT_DELAY_MS, MILLISECONDS);
154 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
155 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
152 >                p.scheduleAtFixedRate(task, timeoutMillis(),
153 >                                      LONG_DELAY_MS, MILLISECONDS);
154 >            await(done);
155 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
156              f.cancel(true);
157          } finally {
158              joinPool(p);
# Line 170 | Line 164 | public class ScheduledExecutorSubclassTe
164       */
165      public void testSchedule5() throws InterruptedException {
166          CustomExecutor p = new CustomExecutor(1);
167 <        final long t0 = System.nanoTime();
174 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
167 >        final long startTime = System.nanoTime();
168          final CountDownLatch done = new CountDownLatch(1);
169          try {
170              Runnable task = new CheckedRunnable() {
171                  public void realRun() {
172                      done.countDown();
173 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
173 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
174                  }};
175              ScheduledFuture f =
176 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
177 <                                         SHORT_DELAY_MS, MILLISECONDS);
178 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
179 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
176 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
177 >                                         LONG_DELAY_MS, MILLISECONDS);
178 >            await(done);
179 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
180              f.cancel(true);
181          } finally {
182              joinPool(p);
# Line 200 | Line 193 | public class ScheduledExecutorSubclassTe
193       */
194      public void testFixedRateSequence() throws InterruptedException {
195          CustomExecutor p = new CustomExecutor(1);
196 <        RunnableCounter counter = new RunnableCounter();
197 <        ScheduledFuture h =
198 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
199 <        Thread.sleep(SMALL_DELAY_MS);
200 <        h.cancel(true);
201 <        int c = counter.count.get();
202 <        // By time scaling conventions, we must have at least
203 <        // an execution per SHORT delay, but no more than one SHORT more
204 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
205 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
206 <        joinPool(p);
196 >        try {
197 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
198 >                long startTime = System.nanoTime();
199 >                int cycles = 10;
200 >                final CountDownLatch done = new CountDownLatch(cycles);
201 >                CheckedRunnable task = new CheckedRunnable() {
202 >                    public void realRun() { done.countDown(); }};
203 >                
204 >                ScheduledFuture h =
205 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
206 >                done.await();
207 >                h.cancel(true);
208 >                double normalizedTime =
209 >                    (double) millisElapsedSince(startTime) / delay;
210 >                if (normalizedTime >= cycles - 1 &&
211 >                    normalizedTime <= cycles)
212 >                    return;
213 >            }
214 >            throw new AssertionError("unexpected execution rate");
215 >        } finally {
216 >            joinPool(p);
217 >        }
218      }
219  
220      /**
# Line 218 | Line 222 | public class ScheduledExecutorSubclassTe
222       */
223      public void testFixedDelaySequence() throws InterruptedException {
224          CustomExecutor p = new CustomExecutor(1);
225 <        RunnableCounter counter = new RunnableCounter();
226 <        ScheduledFuture h =
227 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
228 <        Thread.sleep(SMALL_DELAY_MS);
229 <        h.cancel(true);
230 <        int c = counter.count.get();
231 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
232 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
233 <        joinPool(p);
225 >        try {
226 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
227 >                long startTime = System.nanoTime();
228 >                int cycles = 10;
229 >                final CountDownLatch done = new CountDownLatch(cycles);
230 >                CheckedRunnable task = new CheckedRunnable() {
231 >                    public void realRun() { done.countDown(); }};
232 >                
233 >                ScheduledFuture h =
234 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
235 >                done.await();
236 >                h.cancel(true);
237 >                double normalizedTime =
238 >                    (double) millisElapsedSince(startTime) / delay;
239 >                if (normalizedTime >= cycles - 1 &&
240 >                    normalizedTime <= cycles)
241 >                    return;
242 >            }
243 >            throw new AssertionError("unexpected execution rate");
244 >        } finally {
245 >            joinPool(p);
246 >        }
247      }
248  
232
249      /**
250       * execute(null) throws NPE
251       */
# Line 291 | Line 307 | public class ScheduledExecutorSubclassTe
307      /**
308       * schedule callable throws RejectedExecutionException if shutdown
309       */
310 <     public void testSchedule3_RejectedExecutionException() {
311 <         CustomExecutor se = new CustomExecutor(1);
312 <         try {
313 <             se.shutdown();
314 <             se.schedule(new NoOpCallable(),
315 <                         MEDIUM_DELAY_MS, MILLISECONDS);
316 <             shouldThrow();
317 <         } catch (RejectedExecutionException success) {
318 <         } catch (SecurityException ok) {
319 <         }
320 <         joinPool(se);
310 >    public void testSchedule3_RejectedExecutionException() {
311 >        CustomExecutor se = new CustomExecutor(1);
312 >        try {
313 >            se.shutdown();
314 >            se.schedule(new NoOpCallable(),
315 >                        MEDIUM_DELAY_MS, MILLISECONDS);
316 >            shouldThrow();
317 >        } catch (RejectedExecutionException success) {
318 >        } catch (SecurityException ok) {
319 >        }
320 >        joinPool(se);
321      }
322  
323      /**
# Line 378 | Line 394 | public class ScheduledExecutorSubclassTe
394                      threadProceed.await();
395                      threadDone.countDown();
396                  }});
397 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
397 >            await(threadStarted);
398              assertEquals(0, p.getCompletedTaskCount());
399              threadProceed.countDown();
400              threadDone.await();
401 <            Thread.sleep(SHORT_DELAY_MS);
402 <            assertEquals(1, p.getCompletedTaskCount());
401 >            long startTime = System.nanoTime();
402 >            while (p.getCompletedTaskCount() != 1) {
403 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
404 >                    fail("timed out");
405 >                Thread.yield();
406 >            }
407          } finally {
408              joinPool(p);
409          }
# Line 510 | Line 530 | public class ScheduledExecutorSubclassTe
530      }
531  
532      /**
533 <     * isShutDown is false before shutdown, true after
533 >     * isShutdown is false before shutdown, true after
534       */
535      public void testIsShutdown() {
536          CustomExecutor p = new CustomExecutor(1);
# Line 523 | Line 543 | public class ScheduledExecutorSubclassTe
543          assertTrue(p.isShutdown());
544      }
545  
526
546      /**
547       * isTerminated is false before termination, true after
548       */
# Line 642 | Line 661 | public class ScheduledExecutorSubclassTe
661      public void testPurge() throws InterruptedException {
662          CustomExecutor p = new CustomExecutor(1);
663          ScheduledFuture[] tasks = new ScheduledFuture[5];
664 <        for (int i = 0; i < tasks.length; i++) {
665 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
666 <        }
664 >        for (int i = 0; i < tasks.length; i++)
665 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
666 >                                  LONG_DELAY_MS, MILLISECONDS);
667          try {
668              int max = tasks.length;
669              if (tasks[4].cancel(true)) --max;
670              if (tasks[3].cancel(true)) --max;
671              // There must eventually be an interference-free point at
672              // which purge will not fail. (At worst, when queue is empty.)
673 <            int k;
674 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
673 >            long startTime = System.nanoTime();
674 >            do {
675                  p.purge();
676                  long count = p.getTaskCount();
677 <                if (count >= 0 && count <= max)
678 <                    break;
679 <                Thread.sleep(1);
680 <            }
662 <            assertTrue(k < SMALL_DELAY_MS);
677 >                if (count == max)
678 >                    return;
679 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
680 >            fail("Purge failed to remove cancelled tasks");
681          } finally {
682              for (ScheduledFuture task : tasks)
683                  task.cancel(true);
# Line 668 | Line 686 | public class ScheduledExecutorSubclassTe
686      }
687  
688      /**
689 <     * shutDownNow returns a list containing tasks that were not run
689 >     * shutdownNow returns a list containing tasks that were not run
690       */
691 <    public void testShutDownNow() {
691 >    public void testShutdownNow() {
692          CustomExecutor p = new CustomExecutor(1);
693          for (int i = 0; i < 5; i++)
694 <            p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
695 <        List l;
694 >            p.schedule(new SmallPossiblyInterruptedRunnable(),
695 >                       LONG_DELAY_MS, MILLISECONDS);
696          try {
697 <            l = p.shutdownNow();
697 >            List<Runnable> l = p.shutdownNow();
698 >            assertTrue(p.isShutdown());
699 >            assertEquals(5, l.size());
700          } catch (SecurityException ok) {
701 <            return;
701 >            // Allowed in case test doesn't have privs
702 >        } finally {
703 >            joinPool(p);
704          }
683        assertTrue(p.isShutdown());
684        assertTrue(l.size() > 0 && l.size() <= 5);
685        joinPool(p);
705      }
706  
707      /**
708       * In default setting, shutdown cancels periodic but not delayed
709       * tasks at shutdown
710       */
711 <    public void testShutDown1() throws InterruptedException {
711 >    public void testShutdown1() throws InterruptedException {
712          CustomExecutor p = new CustomExecutor(1);
713          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
714          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
# Line 714 | Line 733 | public class ScheduledExecutorSubclassTe
733          }
734      }
735  
717
736      /**
737       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
738       * delayed tasks are cancelled at shutdown
739       */
740 <    public void testShutDown2() throws InterruptedException {
740 >    public void testShutdown2() throws InterruptedException {
741          CustomExecutor p = new CustomExecutor(1);
742          p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
743          assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
# Line 741 | Line 759 | public class ScheduledExecutorSubclassTe
759          }
760      }
761  
744
762      /**
763       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
764       * periodic tasks are cancelled at shutdown
765       */
766 <    public void testShutDown3() throws InterruptedException {
766 >    public void testShutdown3() throws InterruptedException {
767          CustomExecutor p = new CustomExecutor(1);
768          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
769          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
770          p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
771          assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
772          assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
773 +        long initialDelay = LONG_DELAY_MS;
774          ScheduledFuture task =
775 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
775 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
776 >                                  5, MILLISECONDS);
777          try { p.shutdown(); } catch (SecurityException ok) { return; }
778          assertTrue(p.isShutdown());
760        BlockingQueue q = p.getQueue();
779          assertTrue(p.getQueue().isEmpty());
780          assertTrue(task.isDone());
781          assertTrue(task.isCancelled());
782 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
765 <        assertTrue(p.isTerminated());
782 >        joinPool(p);
783      }
784  
785      /**
786       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
787       * periodic tasks are not cancelled at shutdown
788       */
789 <    public void testShutDown4() throws InterruptedException {
789 >    public void testShutdown4() throws InterruptedException {
790          CustomExecutor p = new CustomExecutor(1);
791          final CountDownLatch counter = new CountDownLatch(2);
792          try {
# Line 1211 | Line 1228 | public class ScheduledExecutorSubclassTe
1228              l.add(new StringTask());
1229              List<Future<String>> futures =
1230                  e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1231 <            assertEquals(3, futures.size());
1232 <            Iterator<Future<String>> it = futures.iterator();
1233 <            Future<String> f1 = it.next();
1234 <            Future<String> f2 = it.next();
1235 <            Future<String> f3 = it.next();
1219 <            assertTrue(f1.isDone());
1220 <            assertTrue(f2.isDone());
1221 <            assertTrue(f3.isDone());
1222 <            assertFalse(f1.isCancelled());
1223 <            assertTrue(f2.isCancelled());
1231 >            assertEquals(l.size(), futures.size());
1232 >            for (Future future : futures)
1233 >                assertTrue(future.isDone());
1234 >            assertFalse(futures.get(0).isCancelled());
1235 >            assertTrue(futures.get(1).isCancelled());
1236          } finally {
1237              joinPool(e);
1238          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines