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.30 by jsr166, Wed Aug 25 00:07:03 2010 UTC vs.
Revision 1.51 by jsr166, Sat Apr 25 04:55:31 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 >
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) {
32 <        junit.textui.TestRunner.run(suite());
32 >        main(suite(), args);
33      }
34      public static Test suite() {
35          return new TestSuite(ScheduledExecutorTest.class);
36      }
37  
23
38      /**
39       * execute successfully executes a runnable
40       */
41      public void testExecute() throws InterruptedException {
42 <        TrackedShortRunnable runnable =new TrackedShortRunnable();
43 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
44 <        p1.execute(runnable);
45 <        assertFalse(runnable.done);
46 <        Thread.sleep(SHORT_DELAY_MS);
47 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
48 <        Thread.sleep(MEDIUM_DELAY_MS);
49 <        assertTrue(runnable.done);
50 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
51 <        joinPool(p1);
42 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
43 >        final CountDownLatch done = new CountDownLatch(1);
44 >        final Runnable task = new CheckedRunnable() {
45 >            public void realRun() {
46 >                done.countDown();
47 >            }};
48 >        try {
49 >            p.execute(task);
50 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
51 >        } finally {
52 >            joinPool(p);
53 >        }
54      }
55  
40
56      /**
57       * delayed schedule of callable successfully executes after delay
58       */
59      public void testSchedule1() throws Exception {
60 <        TrackedCallable callable = new TrackedCallable();
61 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
62 <        Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
63 <        assertFalse(callable.done);
64 <        Thread.sleep(MEDIUM_DELAY_MS);
65 <        assertTrue(callable.done);
66 <        assertEquals(Boolean.TRUE, f.get());
67 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
68 <        joinPool(p1);
60 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
68 >                    return Boolean.TRUE;
69 >                }};
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);
76 >        }
77      }
78  
79      /**
80 <     *  delayed schedule of runnable successfully executes after delay
81 <     */
82 <    public void testSchedule3() throws InterruptedException {
83 <        TrackedShortRunnable runnable = new TrackedShortRunnable();
84 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
85 <        p1.schedule(runnable, SMALL_DELAY_MS, MILLISECONDS);
86 <        Thread.sleep(SHORT_DELAY_MS);
87 <        assertFalse(runnable.done);
88 <        Thread.sleep(MEDIUM_DELAY_MS);
89 <        assertTrue(runnable.done);
90 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
91 <        joinPool(p1);
80 >     * delayed schedule of runnable successfully executes after delay
81 >     */
82 >    public void testSchedule3() throws Exception {
83 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
91 >                }};
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 >        }
99      }
100  
101      /**
102       * scheduleAtFixedRate executes runnable after given initial delay
103       */
104 <    public void testSchedule4() throws InterruptedException {
105 <        TrackedShortRunnable runnable = new TrackedShortRunnable();
106 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
107 <        ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
108 <        assertFalse(runnable.done);
109 <        Thread.sleep(MEDIUM_DELAY_MS);
110 <        assertTrue(runnable.done);
111 <        h.cancel(true);
112 <        joinPool(p1);
113 <    }
114 <
115 <    static class RunnableCounter implements Runnable {
116 <        AtomicInteger count = new AtomicInteger(0);
117 <        public void run() { count.getAndIncrement(); }
104 >    public void testSchedule4() throws Exception {
105 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
113 >                }};
114 >            ScheduledFuture f =
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);
122 >        }
123      }
124  
125      /**
126       * scheduleWithFixedDelay executes runnable after given initial delay
127       */
128 <    public void testSchedule5() throws InterruptedException {
129 <        TrackedShortRunnable runnable = new TrackedShortRunnable();
130 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
131 <        ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
132 <        assertFalse(runnable.done);
133 <        Thread.sleep(MEDIUM_DELAY_MS);
134 <        assertTrue(runnable.done);
135 <        h.cancel(true);
136 <        joinPool(p1);
128 >    public void testSchedule5() throws Exception {
129 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
137 >                }};
138 >            ScheduledFuture f =
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);
146 >        }
147 >    }
148 >
149 >    static class RunnableCounter implements Runnable {
150 >        AtomicInteger count = new AtomicInteger(0);
151 >        public void run() { count.getAndIncrement(); }
152      }
153  
154      /**
155       * scheduleAtFixedRate executes series of tasks at given rate
156       */
157      public void testFixedRateSequence() throws InterruptedException {
158 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
159 <        RunnableCounter counter = new RunnableCounter();
160 <        ScheduledFuture h =
161 <            p1.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
162 <        Thread.sleep(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(p1);
158 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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      /**
183       * scheduleWithFixedDelay executes series of tasks with given period
184       */
185      public void testFixedDelaySequence() throws InterruptedException {
186 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
187 <        RunnableCounter counter = new RunnableCounter();
188 <        ScheduledFuture h =
189 <            p1.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
190 <        Thread.sleep(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(p1);
186 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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  
138
210      /**
211 <     *  execute(null) throws NPE
211 >     * execute(null) throws NPE
212       */
213      public void testExecuteNull() throws InterruptedException {
214          ScheduledThreadPoolExecutor se = null;
# Line 199 | Line 270 | public class ScheduledExecutorTest exten
270      /**
271       * schedule callable throws RejectedExecutionException if shutdown
272       */
273 <     public void testSchedule3_RejectedExecutionException() throws InterruptedException {
274 <         ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
275 <         try {
273 >    public void testSchedule3_RejectedExecutionException() throws InterruptedException {
274 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
275 >        try {
276              se.shutdown();
277              se.schedule(new NoOpCallable(),
278                          MEDIUM_DELAY_MS, MILLISECONDS);
# Line 209 | Line 280 | public class ScheduledExecutorTest exten
280          } catch (RejectedExecutionException success) {
281          } catch (SecurityException ok) {
282          }
283 <         joinPool(se);
283 >        joinPool(se);
284      }
285  
286      /**
287 <     *  scheduleAtFixedRate throws RejectedExecutionException if shutdown
287 >     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
288       */
289      public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
290          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
# Line 245 | Line 316 | public class ScheduledExecutorTest exten
316      }
317  
318      /**
319 <     *  getActiveCount increases but doesn't overestimate, when a
320 <     *  thread becomes active
319 >     * getActiveCount increases but doesn't overestimate, when a
320 >     * thread becomes active
321       */
322      public void testGetActiveCount() throws InterruptedException {
323 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
324 <        assertEquals(0, p2.getActiveCount());
325 <        p2.execute(new SmallRunnable());
326 <        Thread.sleep(SHORT_DELAY_MS);
327 <        assertEquals(1, p2.getActiveCount());
328 <        joinPool(p2);
323 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
324 >        final CountDownLatch threadStarted = new CountDownLatch(1);
325 >        final CountDownLatch done = new CountDownLatch(1);
326 >        try {
327 >            assertEquals(0, p.getActiveCount());
328 >            p.execute(new CheckedRunnable() {
329 >                public void realRun() throws InterruptedException {
330 >                    threadStarted.countDown();
331 >                    assertEquals(1, p.getActiveCount());
332 >                    done.await();
333 >                }});
334 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
335 >            assertEquals(1, p.getActiveCount());
336 >        } finally {
337 >            done.countDown();
338 >            joinPool(p);
339 >        }
340      }
341  
342      /**
343 <     *    getCompletedTaskCount increases, but doesn't overestimate,
344 <     *   when tasks complete
343 >     * getCompletedTaskCount increases, but doesn't overestimate,
344 >     * when tasks complete
345       */
346      public void testGetCompletedTaskCount() throws InterruptedException {
347 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
348 <        assertEquals(0, p2.getCompletedTaskCount());
349 <        p2.execute(new SmallRunnable());
350 <        Thread.sleep(MEDIUM_DELAY_MS);
351 <        assertEquals(1, p2.getCompletedTaskCount());
352 <        joinPool(p2);
347 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
348 >        final CountDownLatch threadStarted = new CountDownLatch(1);
349 >        final CountDownLatch threadProceed = new CountDownLatch(1);
350 >        final CountDownLatch threadDone = new CountDownLatch(1);
351 >        try {
352 >            assertEquals(0, p.getCompletedTaskCount());
353 >            p.execute(new CheckedRunnable() {
354 >                public void realRun() throws InterruptedException {
355 >                    threadStarted.countDown();
356 >                    assertEquals(0, p.getCompletedTaskCount());
357 >                    threadProceed.await();
358 >                    threadDone.countDown();
359 >                }});
360 >            await(threadStarted);
361 >            assertEquals(0, p.getCompletedTaskCount());
362 >            threadProceed.countDown();
363 >            threadDone.await();
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 >        }
373      }
374  
375      /**
376 <     *  getCorePoolSize returns size given in constructor if not otherwise set
376 >     * getCorePoolSize returns size given in constructor if not otherwise set
377       */
378      public void testGetCorePoolSize() throws InterruptedException {
379 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
380 <        assertEquals(1, p1.getCorePoolSize());
381 <        joinPool(p1);
379 >        ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
380 >        assertEquals(1, p.getCorePoolSize());
381 >        joinPool(p);
382      }
383  
384      /**
385 <     *    getLargestPoolSize increases, but doesn't overestimate, when
386 <     *   multiple threads active
385 >     * getLargestPoolSize increases, but doesn't overestimate, when
386 >     * multiple threads active
387       */
388      public void testGetLargestPoolSize() throws InterruptedException {
389 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
390 <        assertEquals(0, p2.getLargestPoolSize());
391 <        p2.execute(new SmallRunnable());
392 <        p2.execute(new SmallRunnable());
393 <        Thread.sleep(SHORT_DELAY_MS);
394 <        assertEquals(2, p2.getLargestPoolSize());
395 <        joinPool(p2);
389 >        final int THREADS = 3;
390 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
391 >        final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
392 >        final CountDownLatch done = new CountDownLatch(1);
393 >        try {
394 >            assertEquals(0, p.getLargestPoolSize());
395 >            for (int i = 0; i < THREADS; i++)
396 >                p.execute(new CheckedRunnable() {
397 >                    public void realRun() throws InterruptedException {
398 >                        threadsStarted.countDown();
399 >                        done.await();
400 >                        assertEquals(THREADS, p.getLargestPoolSize());
401 >                    }});
402 >            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
403 >            assertEquals(THREADS, p.getLargestPoolSize());
404 >        } finally {
405 >            done.countDown();
406 >            joinPool(p);
407 >            assertEquals(THREADS, p.getLargestPoolSize());
408 >        }
409      }
410  
411      /**
412 <     *   getPoolSize increases, but doesn't overestimate, when threads
413 <     *   become active
412 >     * getPoolSize increases, but doesn't overestimate, when threads
413 >     * become active
414       */
415      public void testGetPoolSize() throws InterruptedException {
416 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
417 <        assertEquals(0, p1.getPoolSize());
418 <        p1.execute(new SmallRunnable());
419 <        assertEquals(1, p1.getPoolSize());
420 <        joinPool(p1);
416 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
417 >        final CountDownLatch threadStarted = new CountDownLatch(1);
418 >        final CountDownLatch done = new CountDownLatch(1);
419 >        try {
420 >            assertEquals(0, p.getPoolSize());
421 >            p.execute(new CheckedRunnable() {
422 >                public void realRun() throws InterruptedException {
423 >                    threadStarted.countDown();
424 >                    assertEquals(1, p.getPoolSize());
425 >                    done.await();
426 >                }});
427 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
428 >            assertEquals(1, p.getPoolSize());
429 >        } finally {
430 >            done.countDown();
431 >            joinPool(p);
432 >        }
433      }
434  
435      /**
436 <     *    getTaskCount increases, but doesn't overestimate, when tasks
437 <     *    submitted
436 >     * getTaskCount increases, but doesn't overestimate, when tasks
437 >     * submitted
438       */
439      public void testGetTaskCount() throws InterruptedException {
440 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
441 <        assertEquals(0, p1.getTaskCount());
442 <        for (int i = 0; i < 5; i++)
443 <            p1.execute(new SmallRunnable());
444 <        Thread.sleep(SHORT_DELAY_MS);
445 <        assertEquals(5, p1.getTaskCount());
446 <        joinPool(p1);
440 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
441 >        final CountDownLatch threadStarted = new CountDownLatch(1);
442 >        final CountDownLatch done = new CountDownLatch(1);
443 >        final int TASKS = 5;
444 >        try {
445 >            assertEquals(0, p.getTaskCount());
446 >            for (int i = 0; i < TASKS; i++)
447 >                p.execute(new CheckedRunnable() {
448 >                    public void realRun() throws InterruptedException {
449 >                        threadStarted.countDown();
450 >                        done.await();
451 >                    }});
452 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
453 >            assertEquals(TASKS, p.getTaskCount());
454 >        } finally {
455 >            done.countDown();
456 >            joinPool(p);
457 >        }
458      }
459  
460      /**
# Line 355 | Line 493 | public class ScheduledExecutorTest exten
493      }
494  
495      /**
496 <     *   is isShutDown is false before shutdown, true after
496 >     * isShutdown is false before shutdown, true after
497       */
498      public void testIsShutdown() {
499  
500 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
500 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
501          try {
502 <            assertFalse(p1.isShutdown());
502 >            assertFalse(p.isShutdown());
503          }
504          finally {
505 <            try { p1.shutdown(); } catch (SecurityException ok) { return; }
505 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
506          }
507 <        assertTrue(p1.isShutdown());
507 >        assertTrue(p.isShutdown());
508      }
509  
372
510      /**
511 <     *   isTerminated is false before termination, true after
511 >     * isTerminated is false before termination, true after
512       */
513      public void testIsTerminated() throws InterruptedException {
514 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
514 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
515 >        final CountDownLatch threadStarted = new CountDownLatch(1);
516 >        final CountDownLatch done = new CountDownLatch(1);
517 >        assertFalse(p.isTerminated());
518          try {
519 <            p1.execute(new SmallRunnable());
519 >            p.execute(new CheckedRunnable() {
520 >                public void realRun() throws InterruptedException {
521 >                    assertFalse(p.isTerminated());
522 >                    threadStarted.countDown();
523 >                    done.await();
524 >                }});
525 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
526 >            assertFalse(p.isTerminating());
527 >            done.countDown();
528          } finally {
529 <            try { p1.shutdown(); } catch (SecurityException ok) { return; }
529 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
530          }
531 <        assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
532 <        assertTrue(p1.isTerminated());
531 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
532 >        assertTrue(p.isTerminated());
533      }
534  
535      /**
536 <     *  isTerminating is not true when running or when terminated
536 >     * isTerminating is not true when running or when terminated
537       */
538      public void testIsTerminating() throws InterruptedException {
539 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
540 <        assertFalse(p1.isTerminating());
541 <        try {
542 <            p1.execute(new SmallRunnable());
543 <            assertFalse(p1.isTerminating());
544 <        } finally {
545 <            try { p1.shutdown(); } catch (SecurityException ok) { return; }
546 <        }
547 <
548 <        assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
549 <        assertTrue(p1.isTerminated());
550 <        assertFalse(p1.isTerminating());
539 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
540 >        final CountDownLatch threadStarted = new CountDownLatch(1);
541 >        final CountDownLatch done = new CountDownLatch(1);
542 >        try {
543 >            assertFalse(p.isTerminating());
544 >            p.execute(new CheckedRunnable() {
545 >                public void realRun() throws InterruptedException {
546 >                    assertFalse(p.isTerminating());
547 >                    threadStarted.countDown();
548 >                    done.await();
549 >                }});
550 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
551 >            assertFalse(p.isTerminating());
552 >            done.countDown();
553 >        } finally {
554 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
555 >        }
556 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
557 >        assertTrue(p.isTerminated());
558 >        assertFalse(p.isTerminating());
559      }
560  
561      /**
562       * getQueue returns the work queue, which contains queued tasks
563       */
564      public void testGetQueue() throws InterruptedException {
565 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
566 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
567 <        for (int i = 0; i < 5; i++) {
412 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
413 <        }
565 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
566 >        final CountDownLatch threadStarted = new CountDownLatch(1);
567 >        final CountDownLatch done = new CountDownLatch(1);
568          try {
569 <            Thread.sleep(SHORT_DELAY_MS);
570 <            BlockingQueue<Runnable> q = p1.getQueue();
571 <            assertTrue(q.contains(tasks[4]));
569 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
570 >            for (int i = 0; i < tasks.length; i++) {
571 >                Runnable r = new CheckedRunnable() {
572 >                    public void realRun() throws InterruptedException {
573 >                        threadStarted.countDown();
574 >                        done.await();
575 >                    }};
576 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
577 >            }
578 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
579 >            BlockingQueue<Runnable> q = p.getQueue();
580 >            assertTrue(q.contains(tasks[tasks.length - 1]));
581              assertFalse(q.contains(tasks[0]));
582          } finally {
583 <            joinPool(p1);
583 >            done.countDown();
584 >            joinPool(p);
585          }
586      }
587  
# Line 425 | Line 589 | public class ScheduledExecutorTest exten
589       * remove(task) removes queued task, and fails to remove active task
590       */
591      public void testRemove() throws InterruptedException {
592 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
592 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
593          ScheduledFuture[] tasks = new ScheduledFuture[5];
594 <        for (int i = 0; i < 5; i++) {
595 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
432 <        }
594 >        final CountDownLatch threadStarted = new CountDownLatch(1);
595 >        final CountDownLatch done = new CountDownLatch(1);
596          try {
597 <            Thread.sleep(SHORT_DELAY_MS);
598 <            BlockingQueue<Runnable> q = p1.getQueue();
599 <            assertFalse(p1.remove((Runnable)tasks[0]));
597 >            for (int i = 0; i < tasks.length; i++) {
598 >                Runnable r = new CheckedRunnable() {
599 >                    public void realRun() throws InterruptedException {
600 >                        threadStarted.countDown();
601 >                        done.await();
602 >                    }};
603 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
604 >            }
605 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
606 >            BlockingQueue<Runnable> q = p.getQueue();
607 >            assertFalse(p.remove((Runnable)tasks[0]));
608              assertTrue(q.contains((Runnable)tasks[4]));
609              assertTrue(q.contains((Runnable)tasks[3]));
610 <            assertTrue(p1.remove((Runnable)tasks[4]));
611 <            assertFalse(p1.remove((Runnable)tasks[4]));
610 >            assertTrue(p.remove((Runnable)tasks[4]));
611 >            assertFalse(p.remove((Runnable)tasks[4]));
612              assertFalse(q.contains((Runnable)tasks[4]));
613              assertTrue(q.contains((Runnable)tasks[3]));
614 <            assertTrue(p1.remove((Runnable)tasks[3]));
614 >            assertTrue(p.remove((Runnable)tasks[3]));
615              assertFalse(q.contains((Runnable)tasks[3]));
616          } finally {
617 <            joinPool(p1);
617 >            done.countDown();
618 >            joinPool(p);
619          }
620      }
621  
622      /**
623 <     *  purge removes cancelled tasks from the queue
623 >     * purge eventually removes cancelled tasks from the queue
624       */
625      public void testPurge() throws InterruptedException {
626 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
626 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
627          ScheduledFuture[] tasks = new ScheduledFuture[5];
628 <        for (int i = 0; i < 5; i++) {
629 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
630 <        }
628 >        for (int i = 0; i < tasks.length; i++)
629 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
630 >                                  LONG_DELAY_MS, MILLISECONDS);
631          try {
632 <            int max = 5;
632 >            int max = tasks.length;
633              if (tasks[4].cancel(true)) --max;
634              if (tasks[3].cancel(true)) --max;
635              // There must eventually be an interference-free point at
636              // which purge will not fail. (At worst, when queue is empty.)
637 <            int k;
638 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
639 <                p1.purge();
640 <                long count = p1.getTaskCount();
641 <                if (count >= 0 && count <= max)
642 <                    break;
643 <                Thread.sleep(1);
644 <            }
473 <            assertTrue(k < SMALL_DELAY_MS);
637 >            long startTime = System.nanoTime();
638 >            do {
639 >                p.purge();
640 >                long count = p.getTaskCount();
641 >                if (count == max)
642 >                    return;
643 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
644 >            fail("Purge failed to remove cancelled tasks");
645          } finally {
646 <            joinPool(p1);
646 >            for (ScheduledFuture task : tasks)
647 >                task.cancel(true);
648 >            joinPool(p);
649          }
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() throws InterruptedException {
656 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
655 >    public void testShutdownNow() {
656 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
657          for (int i = 0; i < 5; i++)
658 <            p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
659 <        List l;
658 >            p.schedule(new SmallPossiblyInterruptedRunnable(),
659 >                       LONG_DELAY_MS, MILLISECONDS);
660          try {
661 <            l = p1.shutdownNow();
661 >            List<Runnable> l = p.shutdownNow();
662 >            assertTrue(p.isShutdown());
663 >            assertEquals(5, l.size());
664          } catch (SecurityException ok) {
665 <            return;
665 >            // Allowed in case test doesn't have privs
666 >        } finally {
667 >            joinPool(p);
668          }
492        assertTrue(p1.isShutdown());
493        assertTrue(l.size() > 0 && l.size() <= 5);
494        joinPool(p1);
669      }
670  
671      /**
672       * In default setting, shutdown cancels periodic but not delayed
673       * tasks at shutdown
674       */
675 <    public void testShutDown1() throws InterruptedException {
676 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
677 <        assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
678 <        assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
675 >    public void testShutdown1() throws InterruptedException {
676 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
677 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
678 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
679  
680          ScheduledFuture[] tasks = new ScheduledFuture[5];
681 <        for (int i = 0; i < 5; i++)
682 <            tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
683 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
684 <        BlockingQueue q = p1.getQueue();
685 <        for (Iterator it = q.iterator(); it.hasNext();) {
686 <            ScheduledFuture t = (ScheduledFuture)it.next();
687 <            assertFalse(t.isCancelled());
688 <        }
689 <        assertTrue(p1.isShutdown());
690 <        Thread.sleep(SMALL_DELAY_MS);
691 <        for (int i = 0; i < 5; ++i) {
692 <            assertTrue(tasks[i].isDone());
693 <            assertFalse(tasks[i].isCancelled());
681 >        for (int i = 0; i < tasks.length; i++)
682 >            tasks[i] = p.schedule(new NoOpRunnable(),
683 >                                  SHORT_DELAY_MS, MILLISECONDS);
684 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
685 >        BlockingQueue<Runnable> q = p.getQueue();
686 >        for (ScheduledFuture task : tasks) {
687 >            assertFalse(task.isDone());
688 >            assertFalse(task.isCancelled());
689 >            assertTrue(q.contains(task));
690 >        }
691 >        assertTrue(p.isShutdown());
692 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
693 >        assertTrue(p.isTerminated());
694 >        for (ScheduledFuture task : tasks) {
695 >            assertTrue(task.isDone());
696 >            assertFalse(task.isCancelled());
697          }
698      }
699  
523
700      /**
701       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
702       * delayed tasks are cancelled at shutdown
703       */
704 <    public void testShutDown2() throws InterruptedException {
705 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
706 <        p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
704 >    public void testShutdown2() throws InterruptedException {
705 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
706 >        p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
707 >        assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
708 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
709          ScheduledFuture[] tasks = new ScheduledFuture[5];
710 <        for (int i = 0; i < 5; i++)
711 <            tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
712 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
713 <        assertTrue(p1.isShutdown());
714 <        BlockingQueue q = p1.getQueue();
710 >        for (int i = 0; i < tasks.length; i++)
711 >            tasks[i] = p.schedule(new NoOpRunnable(),
712 >                                  SHORT_DELAY_MS, MILLISECONDS);
713 >        BlockingQueue q = p.getQueue();
714 >        assertEquals(tasks.length, q.size());
715 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
716 >        assertTrue(p.isShutdown());
717          assertTrue(q.isEmpty());
718 <        Thread.sleep(SMALL_DELAY_MS);
719 <        assertTrue(p1.isTerminated());
718 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
719 >        assertTrue(p.isTerminated());
720 >        for (ScheduledFuture task : tasks) {
721 >            assertTrue(task.isDone());
722 >            assertTrue(task.isCancelled());
723 >        }
724      }
725  
542
726      /**
727       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
728 <     * periodic tasks are not cancelled at shutdown
728 >     * periodic tasks are cancelled at shutdown
729       */
730 <    public void testShutDown3() throws InterruptedException {
731 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
732 <        p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
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 <            p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
740 <        try { p1.shutdown(); } catch (SecurityException ok) { return; }
741 <        assertTrue(p1.isShutdown());
742 <        BlockingQueue q = p1.getQueue();
743 <        assertTrue(q.isEmpty());
744 <        Thread.sleep(SHORT_DELAY_MS);
745 <        assertTrue(p1.isTerminated());
739 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
740 >                                  5, MILLISECONDS);
741 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
742 >        assertTrue(p.isShutdown());
743 >        assertTrue(p.getQueue().isEmpty());
744 >        assertTrue(task.isDone());
745 >        assertTrue(task.isCancelled());
746 >        joinPool(p);
747      }
748  
749      /**
750       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
751 <     * periodic tasks are cancelled at shutdown
751 >     * periodic tasks are not cancelled at shutdown
752       */
753 <    public void testShutDown4() throws InterruptedException {
754 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
753 >    public void testShutdown4() throws InterruptedException {
754 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
755 >        final CountDownLatch counter = new CountDownLatch(2);
756          try {
757 <            p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
757 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
758 >            assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
759 >            assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
760 >            final Runnable r = new CheckedRunnable() {
761 >                public void realRun() {
762 >                    counter.countDown();
763 >                }};
764              ScheduledFuture task =
765 <                p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, MILLISECONDS);
765 >                p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS);
766 >            assertFalse(task.isDone());
767              assertFalse(task.isCancelled());
768 <            try { p1.shutdown(); } catch (SecurityException ok) { return; }
768 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
769              assertFalse(task.isCancelled());
770 <            assertFalse(p1.isTerminated());
771 <            assertTrue(p1.isShutdown());
772 <            Thread.sleep(SHORT_DELAY_MS);
770 >            assertFalse(p.isTerminated());
771 >            assertTrue(p.isShutdown());
772 >            assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS));
773              assertFalse(task.isCancelled());
774 <            assertTrue(task.cancel(true));
774 >            assertTrue(task.cancel(false));
775              assertTrue(task.isDone());
776 <            Thread.sleep(SHORT_DELAY_MS);
777 <            assertTrue(p1.isTerminated());
776 >            assertTrue(task.isCancelled());
777 >            assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
778 >            assertTrue(p.isTerminated());
779          }
780          finally {
781 <            joinPool(p1);
781 >            joinPool(p);
782          }
783      }
784  
# Line 994 | 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();
1002 <            assertTrue(f1.isDone());
1003 <            assertTrue(f2.isDone());
1004 <            assertTrue(f3.isDone());
1005 <            assertFalse(f1.isCancelled());
1006 <            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  
1012
1205   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines