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.18 by dl, Wed Jan 21 01:47:07 2004 UTC vs.
Revision 1.56 by jsr166, Mon Sep 28 02:41:29 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
5 < * Other contributors include Andrew Wright, Jeffrey Hayes,
6 < * Pat Fisher, Mike Judd.
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.*;
12 < import java.util.concurrent.atomic.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
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);
38 >        return new TestSuite(ScheduledExecutorTest.class);
39      }
40  
22
41      /**
42       * execute successfully executes a runnable
43       */
44 <    public void testExecute() {
45 <        try {
46 <            TrackedShortRunnable runnable =new TrackedShortRunnable();
47 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
48 <            p1.execute(runnable);
49 <            assertFalse(runnable.done);
50 <            Thread.sleep(SHORT_DELAY_MS);
51 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
52 <            try {
53 <                Thread.sleep(MEDIUM_DELAY_MS);
54 <            } catch(InterruptedException e){
55 <                unexpectedException();
38 <            }
39 <            assertTrue(runnable.done);
40 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
41 <            joinPool(p1);
42 <        }
43 <        catch(Exception e){
44 <            unexpectedException();
44 >    public void testExecute() throws InterruptedException {
45 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
46 >        final CountDownLatch done = new CountDownLatch(1);
47 >        final Runnable task = new CheckedRunnable() {
48 >            public void realRun() {
49 >                done.countDown();
50 >            }};
51 >        try {
52 >            p.execute(task);
53 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
54 >        } finally {
55 >            joinPool(p);
56          }
46        
57      }
58  
49
59      /**
60       * delayed schedule of callable successfully executes after delay
61       */
62 <    public void testSchedule1() {
63 <        try {
64 <            TrackedCallable callable = new TrackedCallable();
65 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
66 <            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
67 <            assertFalse(callable.done);
68 <            Thread.sleep(MEDIUM_DELAY_MS);
69 <            assertTrue(callable.done);
70 <            assertEquals(Boolean.TRUE, f.get());
71 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
72 <            joinPool(p1);
73 <        } catch(RejectedExecutionException e){}
74 <        catch(Exception e){
75 <            e.printStackTrace();
76 <            unexpectedException();
62 >    public void testSchedule1() throws Exception {
63 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
71 >                    return Boolean.TRUE;
72 >                }};
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);
79          }
80      }
81  
82      /**
83 <     *  delayed schedule of runnable successfully executes after delay
84 <     */
85 <    public void testSchedule3() {
86 <        try {
87 <            TrackedShortRunnable runnable = new TrackedShortRunnable();
88 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
89 <            p1.schedule(runnable, SMALL_DELAY_MS, TimeUnit.MILLISECONDS);
90 <            Thread.sleep(SHORT_DELAY_MS);
91 <            assertFalse(runnable.done);
92 <            Thread.sleep(MEDIUM_DELAY_MS);
93 <            assertTrue(runnable.done);
94 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
95 <            joinPool(p1);
96 <        } catch(Exception e){
97 <            unexpectedException();
83 >     * delayed schedule of runnable successfully executes after delay
84 >     */
85 >    public void testSchedule3() throws Exception {
86 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
94 >                }};
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          }
102      }
103 <    
103 >
104      /**
105       * scheduleAtFixedRate executes runnable after given initial delay
106       */
107 <    public void testSchedule4() {
108 <        try {
109 <            TrackedShortRunnable runnable = new TrackedShortRunnable();
110 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
111 <            ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
112 <            assertFalse(runnable.done);
113 <            Thread.sleep(MEDIUM_DELAY_MS);
114 <            assertTrue(runnable.done);
115 <            h.cancel(true);
116 <            joinPool(p1);
117 <        } catch(Exception e){
118 <            unexpectedException();
107 >    public void testSchedule4() throws Exception {
108 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
116 >                }};
117 >            ScheduledFuture f =
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);
125          }
126      }
127  
108    static class RunnableCounter implements Runnable {
109        AtomicInteger count = new AtomicInteger(0);
110        public void run() { count.getAndIncrement(); }
111    }
112
128      /**
129       * scheduleWithFixedDelay executes runnable after given initial delay
130       */
131 <    public void testSchedule5() {
132 <        try {
133 <            TrackedShortRunnable runnable = new TrackedShortRunnable();
134 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
135 <            ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
136 <            assertFalse(runnable.done);
137 <            Thread.sleep(MEDIUM_DELAY_MS);
138 <            assertTrue(runnable.done);
139 <            h.cancel(true);
140 <            joinPool(p1);
141 <        } catch(Exception e){
142 <            unexpectedException();
131 >    public void testSchedule5() throws Exception {
132 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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(millisElapsedSince(startTime) >= timeoutMillis());
140 >                }};
141 >            ScheduledFuture f =
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);
149          }
150      }
151 <    
151 >
152 >    static class RunnableCounter implements Runnable {
153 >        AtomicInteger count = new AtomicInteger(0);
154 >        public void run() { count.getAndIncrement(); }
155 >    }
156 >
157      /**
158       * scheduleAtFixedRate executes series of tasks at given rate
159       */
160 <    public void testFixedRateSequence() {
161 <        try {
162 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
163 <            RunnableCounter counter = new RunnableCounter();
164 <            ScheduledFuture h =
165 <                p1.scheduleAtFixedRate(counter, 0, 1, TimeUnit.MILLISECONDS);
166 <            Thread.sleep(SMALL_DELAY_MS);
167 <            h.cancel(true);
168 <            int c = counter.count.get();
169 <            // By time scaling conventions, we must have at least
170 <            // an execution per SHORT delay, but no more than one SHORT more
171 <            assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
172 <            assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
173 <            assertTrue(h.isDone());
174 <            joinPool(p1);
175 <        } catch(Exception e){
176 <            unexpectedException();
160 >    public void testFixedRateSequence() throws InterruptedException {
161 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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      /**
186       * scheduleWithFixedDelay executes series of tasks with given period
187       */
188 <    public void testFixedDelaySequence() {
189 <        try {
190 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
191 <            RunnableCounter counter = new RunnableCounter();
192 <            ScheduledFuture h =
193 <                p1.scheduleWithFixedDelay(counter, 0, 1, TimeUnit.MILLISECONDS);
194 <            Thread.sleep(SMALL_DELAY_MS);
195 <            h.cancel(true);
196 <            int c = counter.count.get();
197 <            assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
198 <            assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
199 <            assertTrue(h.isDone());
200 <            joinPool(p1);
201 <        } catch(Exception e){
202 <            unexpectedException();
188 >    public void testFixedDelaySequence() throws InterruptedException {
189 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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  
175
213      /**
214 <     *  execute (null) throws NPE
214 >     * execute(null) throws NPE
215       */
216 <    public void testExecuteNull() {
216 >    public void testExecuteNull() throws InterruptedException {
217          ScheduledThreadPoolExecutor se = null;
218          try {
219 <            se = new ScheduledThreadPoolExecutor(1);
220 <            se.execute(null);
219 >            se = new ScheduledThreadPoolExecutor(1);
220 >            se.execute(null);
221              shouldThrow();
222 <        } catch(NullPointerException success){}
223 <        catch(Exception e){
224 <            unexpectedException();
188 <        }
189 <        
190 <        joinPool(se);
222 >        } catch (NullPointerException success) {}
223 >
224 >        joinPool(se);
225      }
226  
227      /**
228 <     * schedule (null) throws NPE
228 >     * schedule(null) throws NPE
229       */
230 <    public void testScheduleNull() {
230 >    public void testScheduleNull() throws InterruptedException {
231          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
232 <        try {
232 >        try {
233              TrackedCallable callable = null;
234 <            Future f = se.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
234 >            Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
235              shouldThrow();
236 <        } catch(NullPointerException success){}
237 <        catch(Exception e){
204 <            unexpectedException();
205 <        }
206 <        joinPool(se);
236 >        } catch (NullPointerException success) {}
237 >        joinPool(se);
238      }
239 <  
239 >
240      /**
241       * execute throws RejectedExecutionException if shutdown
242       */
243 <    public void testSchedule1_RejectedExecutionException() {
243 >    public void testSchedule1_RejectedExecutionException() throws InterruptedException {
244          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
245          try {
246              se.shutdown();
247              se.schedule(new NoOpRunnable(),
248 <                        MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
248 >                        MEDIUM_DELAY_MS, MILLISECONDS);
249              shouldThrow();
250 <        } catch(RejectedExecutionException success){
250 >        } catch (RejectedExecutionException success) {
251          } catch (SecurityException ok) {
252          }
222        
223        joinPool(se);
253  
254 +        joinPool(se);
255      }
256  
257      /**
258       * schedule throws RejectedExecutionException if shutdown
259       */
260 <    public void testSchedule2_RejectedExecutionException() {
260 >    public void testSchedule2_RejectedExecutionException() throws InterruptedException {
261          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
262          try {
263              se.shutdown();
264              se.schedule(new NoOpCallable(),
265 <                        MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
265 >                        MEDIUM_DELAY_MS, MILLISECONDS);
266              shouldThrow();
267 <        } catch(RejectedExecutionException success){
267 >        } catch (RejectedExecutionException success) {
268          } catch (SecurityException ok) {
269          }
270          joinPool(se);
# Line 243 | Line 273 | public class ScheduledExecutorTest exten
273      /**
274       * schedule callable throws RejectedExecutionException if shutdown
275       */
276 <     public void testSchedule3_RejectedExecutionException() {
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, TimeUnit.MILLISECONDS);
281 >                        MEDIUM_DELAY_MS, MILLISECONDS);
282              shouldThrow();
283 <        } catch(RejectedExecutionException success){
283 >        } catch (RejectedExecutionException success) {
284          } catch (SecurityException ok) {
285          }
286 <         joinPool(se);
286 >        joinPool(se);
287      }
288  
289      /**
290 <     *  scheduleAtFixedRate throws RejectedExecutionException if shutdown
290 >     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
291       */
292 <    public void testScheduleAtFixedRate1_RejectedExecutionException() {
292 >    public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
293          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
294          try {
295              se.shutdown();
296              se.scheduleAtFixedRate(new NoOpRunnable(),
297 <                                   MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
297 >                                   MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
298              shouldThrow();
299 <        } catch(RejectedExecutionException success){
299 >        } catch (RejectedExecutionException success) {
300          } catch (SecurityException ok) {
301 <        }
301 >        }
302          joinPool(se);
303      }
304 <    
304 >
305      /**
306       * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
307       */
308 <    public void testScheduleWithFixedDelay1_RejectedExecutionException() {
308 >    public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
309          ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
310          try {
311              se.shutdown();
312              se.scheduleWithFixedDelay(new NoOpRunnable(),
313 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
313 >                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
314              shouldThrow();
315 <        } catch(RejectedExecutionException success){
315 >        } catch (RejectedExecutionException success) {
316          } catch (SecurityException ok) {
317 <        }
317 >        }
318          joinPool(se);
319      }
320  
321      /**
322 <     *  getActiveCount increases but doesn't overestimate, when a
323 <     *  thread becomes active
322 >     * getActiveCount increases but doesn't overestimate, when a
323 >     * thread becomes active
324       */
325 <    public void testGetActiveCount() {
326 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
327 <        assertEquals(0, p2.getActiveCount());
328 <        p2.execute(new SmallRunnable());
329 <        try {
330 <            Thread.sleep(SHORT_DELAY_MS);
331 <        } catch(Exception e){
332 <            unexpectedException();
325 >    public void testGetActiveCount() throws InterruptedException {
326 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
327 >        final CountDownLatch threadStarted = new CountDownLatch(1);
328 >        final CountDownLatch done = new CountDownLatch(1);
329 >        try {
330 >            assertEquals(0, p.getActiveCount());
331 >            p.execute(new CheckedRunnable() {
332 >                public void realRun() throws InterruptedException {
333 >                    threadStarted.countDown();
334 >                    assertEquals(1, p.getActiveCount());
335 >                    done.await();
336 >                }});
337 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
338 >            assertEquals(1, p.getActiveCount());
339 >        } finally {
340 >            done.countDown();
341 >            joinPool(p);
342          }
304        assertEquals(1, p2.getActiveCount());
305        joinPool(p2);
343      }
344 <    
344 >
345      /**
346 <     *    getCompletedTaskCount increases, but doesn't overestimate,
347 <     *   when tasks complete
346 >     * getCompletedTaskCount increases, but doesn't overestimate,
347 >     * when tasks complete
348       */
349 <    public void testGetCompletedTaskCount() {
350 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
351 <        assertEquals(0, p2.getCompletedTaskCount());
352 <        p2.execute(new SmallRunnable());
353 <        try {
354 <            Thread.sleep(MEDIUM_DELAY_MS);
355 <        } catch(Exception e){
356 <            unexpectedException();
349 >    public void testGetCompletedTaskCount() throws InterruptedException {
350 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
351 >        final CountDownLatch threadStarted = new CountDownLatch(1);
352 >        final CountDownLatch threadProceed = new CountDownLatch(1);
353 >        final CountDownLatch threadDone = new CountDownLatch(1);
354 >        try {
355 >            assertEquals(0, p.getCompletedTaskCount());
356 >            p.execute(new CheckedRunnable() {
357 >                public void realRun() throws InterruptedException {
358 >                    threadStarted.countDown();
359 >                    assertEquals(0, p.getCompletedTaskCount());
360 >                    threadProceed.await();
361 >                    threadDone.countDown();
362 >                }});
363 >            await(threadStarted);
364 >            assertEquals(0, p.getCompletedTaskCount());
365 >            threadProceed.countDown();
366 >            threadDone.await();
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          }
321        assertEquals(1, p2.getCompletedTaskCount());
322        joinPool(p2);
376      }
377 <    
377 >
378      /**
379 <     *  getCorePoolSize returns size given in constructor if not otherwise set
379 >     * getCorePoolSize returns size given in constructor if not otherwise set
380       */
381 <    public void testGetCorePoolSize() {
382 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
383 <        assertEquals(1, p1.getCorePoolSize());
384 <        joinPool(p1);
381 >    public void testGetCorePoolSize() throws InterruptedException {
382 >        ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
383 >        assertEquals(1, p.getCorePoolSize());
384 >        joinPool(p);
385      }
386 <    
386 >
387      /**
388 <     *    getLargestPoolSize increases, but doesn't overestimate, when
389 <     *   multiple threads active
388 >     * getLargestPoolSize increases, but doesn't overestimate, when
389 >     * multiple threads active
390       */
391 <    public void testGetLargestPoolSize() {
392 <        ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
393 <        assertEquals(0, p2.getLargestPoolSize());
394 <        p2.execute(new SmallRunnable());
395 <        p2.execute(new SmallRunnable());
396 <        try {
397 <            Thread.sleep(SHORT_DELAY_MS);
398 <        } catch(Exception e){
399 <            unexpectedException();
391 >    public void testGetLargestPoolSize() throws InterruptedException {
392 >        final int THREADS = 3;
393 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
394 >        final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
395 >        final CountDownLatch done = new CountDownLatch(1);
396 >        try {
397 >            assertEquals(0, p.getLargestPoolSize());
398 >            for (int i = 0; i < THREADS; i++)
399 >                p.execute(new CheckedRunnable() {
400 >                    public void realRun() throws InterruptedException {
401 >                        threadsStarted.countDown();
402 >                        done.await();
403 >                        assertEquals(THREADS, p.getLargestPoolSize());
404 >                    }});
405 >            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
406 >            assertEquals(THREADS, p.getLargestPoolSize());
407 >        } finally {
408 >            done.countDown();
409 >            joinPool(p);
410 >            assertEquals(THREADS, p.getLargestPoolSize());
411          }
348        assertEquals(2, p2.getLargestPoolSize());
349        joinPool(p2);
412      }
413 <    
413 >
414      /**
415 <     *   getPoolSize increases, but doesn't overestimate, when threads
416 <     *   become active
415 >     * getPoolSize increases, but doesn't overestimate, when threads
416 >     * become active
417       */
418 <    public void testGetPoolSize() {
419 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
420 <        assertEquals(0, p1.getPoolSize());
421 <        p1.execute(new SmallRunnable());
422 <        assertEquals(1, p1.getPoolSize());
423 <        joinPool(p1);
418 >    public void testGetPoolSize() throws InterruptedException {
419 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
420 >        final CountDownLatch threadStarted = new CountDownLatch(1);
421 >        final CountDownLatch done = new CountDownLatch(1);
422 >        try {
423 >            assertEquals(0, p.getPoolSize());
424 >            p.execute(new CheckedRunnable() {
425 >                public void realRun() throws InterruptedException {
426 >                    threadStarted.countDown();
427 >                    assertEquals(1, p.getPoolSize());
428 >                    done.await();
429 >                }});
430 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
431 >            assertEquals(1, p.getPoolSize());
432 >        } finally {
433 >            done.countDown();
434 >            joinPool(p);
435 >        }
436      }
437 <    
437 >
438      /**
439 <     *    getTaskCount increases, but doesn't overestimate, when tasks
440 <     *    submitted
439 >     * getTaskCount increases, but doesn't overestimate, when tasks
440 >     * submitted
441       */
442 <    public void testGetTaskCount() {
443 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
444 <        assertEquals(0, p1.getTaskCount());
445 <        for(int i = 0; i < 5; i++)
446 <            p1.execute(new SmallRunnable());
447 <        try {
448 <            Thread.sleep(SHORT_DELAY_MS);
449 <        } catch(Exception e){
450 <            unexpectedException();
442 >    public void testGetTaskCount() throws InterruptedException {
443 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
444 >        final CountDownLatch threadStarted = new CountDownLatch(1);
445 >        final CountDownLatch done = new CountDownLatch(1);
446 >        final int TASKS = 5;
447 >        try {
448 >            assertEquals(0, p.getTaskCount());
449 >            for (int i = 0; i < TASKS; i++)
450 >                p.execute(new CheckedRunnable() {
451 >                    public void realRun() throws InterruptedException {
452 >                        threadStarted.countDown();
453 >                        done.await();
454 >                    }});
455 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
456 >            assertEquals(TASKS, p.getTaskCount());
457 >        } finally {
458 >            done.countDown();
459 >            joinPool(p);
460          }
378        assertEquals(5, p1.getTaskCount());
379        joinPool(p1);
461      }
462  
463 <    /**
463 >    /**
464       * getThreadFactory returns factory in constructor if not set
465       */
466 <    public void testGetThreadFactory() {
466 >    public void testGetThreadFactory() throws InterruptedException {
467          ThreadFactory tf = new SimpleThreadFactory();
468 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
468 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
469          assertSame(tf, p.getThreadFactory());
470          joinPool(p);
471      }
472  
473 <    /**
473 >    /**
474       * setThreadFactory sets the thread factory returned by getThreadFactory
475       */
476 <    public void testSetThreadFactory() {
476 >    public void testSetThreadFactory() throws InterruptedException {
477          ThreadFactory tf = new SimpleThreadFactory();
478 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
478 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
479          p.setThreadFactory(tf);
480          assertSame(tf, p.getThreadFactory());
481          joinPool(p);
482      }
483  
484 <    /**
484 >    /**
485       * setThreadFactory(null) throws NPE
486       */
487 <    public void testSetThreadFactoryNull() {
488 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
487 >    public void testSetThreadFactoryNull() throws InterruptedException {
488 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
489          try {
490              p.setThreadFactory(null);
491              shouldThrow();
# Line 413 | Line 494 | public class ScheduledExecutorTest exten
494              joinPool(p);
495          }
496      }
497 <    
497 >
498      /**
499 <     *   is isShutDown is false before shutdown, true after
499 >     * isShutdown is false before shutdown, true after
500       */
501      public void testIsShutdown() {
502 <        
503 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
502 >
503 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
504          try {
505 <            assertFalse(p1.isShutdown());
505 >            assertFalse(p.isShutdown());
506          }
507          finally {
508 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
508 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
509          }
510 <        assertTrue(p1.isShutdown());
510 >        assertTrue(p.isShutdown());
511      }
512  
432        
513      /**
514 <     *   isTerminated is false before termination, true after
514 >     * isTerminated is false before termination, true after
515       */
516 <    public void testIsTerminated() {
517 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
516 >    public void testIsTerminated() throws InterruptedException {
517 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
518 >        final CountDownLatch threadStarted = new CountDownLatch(1);
519 >        final CountDownLatch done = new CountDownLatch(1);
520 >        assertFalse(p.isTerminated());
521          try {
522 <            p1.execute(new SmallRunnable());
522 >            p.execute(new CheckedRunnable() {
523 >                public void realRun() throws InterruptedException {
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 { p1.shutdown(); } catch(SecurityException ok) { return; }
532 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
533          }
534 <        try {
535 <            assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
445 <            assertTrue(p1.isTerminated());
446 <        } catch(Exception e){
447 <            unexpectedException();
448 <        }      
534 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
535 >        assertTrue(p.isTerminated());
536      }
537  
538      /**
539 <     *  isTerminating is not true when running or when terminated
539 >     * isTerminating is not true when running or when terminated
540       */
541 <    public void testIsTerminating() {
542 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
543 <        assertFalse(p1.isTerminating());
541 >    public void testIsTerminating() throws InterruptedException {
542 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
543 >        final CountDownLatch threadStarted = new CountDownLatch(1);
544 >        final CountDownLatch done = new CountDownLatch(1);
545          try {
546 <            p1.execute(new SmallRunnable());
547 <            assertFalse(p1.isTerminating());
546 >            assertFalse(p.isTerminating());
547 >            p.execute(new CheckedRunnable() {
548 >                public void realRun() throws InterruptedException {
549 >                    assertFalse(p.isTerminating());
550 >                    threadStarted.countDown();
551 >                    done.await();
552 >                }});
553 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
554 >            assertFalse(p.isTerminating());
555 >            done.countDown();
556          } finally {
557 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
557 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
558          }
559 <        try {
560 <            assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
561 <            assertTrue(p1.isTerminated());
466 <            assertFalse(p1.isTerminating());
467 <        } catch(Exception e){
468 <            unexpectedException();
469 <        }      
559 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
560 >        assertTrue(p.isTerminated());
561 >        assertFalse(p.isTerminating());
562      }
563  
564      /**
565       * getQueue returns the work queue, which contains queued tasks
566       */
567 <    public void testGetQueue() {
568 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
569 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
570 <        for(int i = 0; i < 5; i++){
479 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
480 <        }
567 >    public void testGetQueue() throws InterruptedException {
568 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
569 >        final CountDownLatch threadStarted = new CountDownLatch(1);
570 >        final CountDownLatch done = new CountDownLatch(1);
571          try {
572 <            Thread.sleep(SHORT_DELAY_MS);
573 <            BlockingQueue<Runnable> q = p1.getQueue();
574 <            assertTrue(q.contains(tasks[4]));
572 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
573 >            for (int i = 0; i < tasks.length; i++) {
574 >                Runnable r = new CheckedRunnable() {
575 >                    public void realRun() throws InterruptedException {
576 >                        threadStarted.countDown();
577 >                        done.await();
578 >                    }};
579 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
580 >            }
581 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
582 >            BlockingQueue<Runnable> q = p.getQueue();
583 >            assertTrue(q.contains(tasks[tasks.length - 1]));
584              assertFalse(q.contains(tasks[0]));
486        } catch(Exception e) {
487            unexpectedException();
585          } finally {
586 <            joinPool(p1);
586 >            done.countDown();
587 >            joinPool(p);
588          }
589      }
590  
591      /**
592       * remove(task) removes queued task, and fails to remove active task
593       */
594 <    public void testRemove() {
595 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
594 >    public void testRemove() throws InterruptedException {
595 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
596          ScheduledFuture[] tasks = new ScheduledFuture[5];
597 <        for(int i = 0; i < 5; i++){
598 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
501 <        }
597 >        final CountDownLatch threadStarted = new CountDownLatch(1);
598 >        final CountDownLatch done = new CountDownLatch(1);
599          try {
600 <            Thread.sleep(SHORT_DELAY_MS);
601 <            BlockingQueue<Runnable> q = p1.getQueue();
602 <            assertFalse(p1.remove((Runnable)tasks[0]));
600 >            for (int i = 0; i < tasks.length; i++) {
601 >                Runnable r = new CheckedRunnable() {
602 >                    public void realRun() throws InterruptedException {
603 >                        threadStarted.countDown();
604 >                        done.await();
605 >                    }};
606 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
607 >            }
608 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
609 >            BlockingQueue<Runnable> q = p.getQueue();
610 >            assertFalse(p.remove((Runnable)tasks[0]));
611              assertTrue(q.contains((Runnable)tasks[4]));
612              assertTrue(q.contains((Runnable)tasks[3]));
613 <            assertTrue(p1.remove((Runnable)tasks[4]));
614 <            assertFalse(p1.remove((Runnable)tasks[4]));
613 >            assertTrue(p.remove((Runnable)tasks[4]));
614 >            assertFalse(p.remove((Runnable)tasks[4]));
615              assertFalse(q.contains((Runnable)tasks[4]));
616              assertTrue(q.contains((Runnable)tasks[3]));
617 <            assertTrue(p1.remove((Runnable)tasks[3]));
617 >            assertTrue(p.remove((Runnable)tasks[3]));
618              assertFalse(q.contains((Runnable)tasks[3]));
514        } catch(Exception e) {
515            unexpectedException();
619          } finally {
620 <            joinPool(p1);
620 >            done.countDown();
621 >            joinPool(p);
622          }
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() {
629 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
628 >    public void testPurge() throws InterruptedException {
629 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
630          ScheduledFuture[] tasks = new ScheduledFuture[5];
631 <        for(int i = 0; i < 5; i++){
632 <            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
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 >            long startTime = System.nanoTime();
641 >            do {
642 >                p.purge();
643 >                long count = p.getTaskCount();
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);
651 >            joinPool(p);
652 >        }
653 >    }
654 >
655 >    /**
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 {
660 >        final int poolSize = 2;
661 >        final int count = 5;
662 >        final AtomicInteger ran = new AtomicInteger(0);
663 >        final ScheduledThreadPoolExecutor p =
664 >            new ScheduledThreadPoolExecutor(poolSize);
665 >        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
666 >        CheckedRunnable waiter = new CheckedRunnable() { public void realRun() {
667 >            threadsStarted.countDown();
668 >            try {
669 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
670 >            } catch (InterruptedException success) {}
671 >            ran.getAndIncrement();
672 >        }};
673 >        for (int i = 0; i < count; i++)
674 >            p.execute(waiter);
675 >        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
676 >        final List<Runnable> queuedTasks;
677 >        try {
678 >            queuedTasks = p.shutdownNow();
679 >        } catch (SecurityException ok) {
680 >            return; // Allowed in case test doesn't have privs
681          }
682 <        int max = 5;
683 <        if (tasks[4].cancel(true)) --max;
684 <        if (tasks[3].cancel(true)) --max;
685 <        p1.purge();
686 <        long count = p1.getTaskCount();
687 <        assertTrue(count > 0 && count <= max);
536 <        joinPool(p1);
682 >        assertTrue(p.isShutdown());
683 >        assertTrue(p.getQueue().isEmpty());
684 >        assertEquals(count - poolSize, queuedTasks.size());
685 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
686 >        assertTrue(p.isTerminated());
687 >        assertEquals(poolSize, ran.get());
688      }
689  
690      /**
691 <     *  shutDownNow returns a list containing tasks that were not run
692 <     */
693 <    public void testShutDownNow() {
694 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
695 <        for(int i = 0; i < 5; i++)
696 <            p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
697 <        List l;
698 <        try {
699 <            l = p1.shutdownNow();
700 <        } catch (SecurityException ok) {
701 <            return;
702 <        }
703 <        assertTrue(p1.isShutdown());
704 <        assertTrue(l.size() > 0 && l.size() <= 5);
705 <        joinPool(p1);
691 >     * shutdownNow returns a list containing tasks that were not run,
692 >     * and those tasks are drained from the queue
693 >     */
694 >    public void testShutdownNow_delayedTasks() throws InterruptedException {
695 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
696 >        List<ScheduledFuture> tasks = new ArrayList<>();
697 >        for (int i = 0; i < 3; i++) {
698 >            Runnable r = new NoOpRunnable();
699 >            tasks.add(p.schedule(r, 9, SECONDS));
700 >            tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
701 >            tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
702 >        }
703 >        if (testImplementationDetails)
704 >            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
705 >        final List<Runnable> queuedTasks;
706 >        try {
707 >            queuedTasks = p.shutdownNow();
708 >        } catch (SecurityException ok) {
709 >            return; // Allowed in case test doesn't have privs
710 >        }
711 >        assertTrue(p.isShutdown());
712 >        assertTrue(p.getQueue().isEmpty());
713 >        if (testImplementationDetails)
714 >            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
715 >        assertEquals(tasks.size(), queuedTasks.size());
716 >        for (ScheduledFuture task : tasks) {
717 >            assertFalse(task.isDone());
718 >            assertFalse(task.isCancelled());
719 >        }
720 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
721 >        assertTrue(p.isTerminated());
722      }
723  
724      /**
725       * In default setting, shutdown cancels periodic but not delayed
726       * tasks at shutdown
727       */
728 <    public void testShutDown1() {
729 <        try {
730 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
731 <            assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
565 <            assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
728 >    public void testShutdown1() throws InterruptedException {
729 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
730 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
731 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
732  
733 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
734 <            for(int i = 0; i < 5; i++)
735 <                tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
736 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
737 <            BlockingQueue q = p1.getQueue();
738 <            for (Iterator it = q.iterator(); it.hasNext();) {
739 <                ScheduledFuture t = (ScheduledFuture)it.next();
740 <                assertFalse(t.isCancelled());
741 <            }
742 <            assertTrue(p1.isShutdown());
577 <            Thread.sleep(SMALL_DELAY_MS);
578 <            for (int i = 0; i < 5; ++i) {
579 <                assertTrue(tasks[i].isDone());
580 <                assertFalse(tasks[i].isCancelled());
581 <            }
582 <            
733 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
734 >        for (int i = 0; i < tasks.length; i++)
735 >            tasks[i] = p.schedule(new NoOpRunnable(),
736 >                                  SHORT_DELAY_MS, MILLISECONDS);
737 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
738 >        BlockingQueue<Runnable> q = p.getQueue();
739 >        for (ScheduledFuture task : tasks) {
740 >            assertFalse(task.isDone());
741 >            assertFalse(task.isCancelled());
742 >            assertTrue(q.contains(task));
743          }
744 <        catch(Exception ex) {
745 <            unexpectedException();
744 >        assertTrue(p.isShutdown());
745 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
746 >        assertTrue(p.isTerminated());
747 >        for (ScheduledFuture task : tasks) {
748 >            assertTrue(task.isDone());
749 >            assertFalse(task.isCancelled());
750          }
751      }
752  
589
753      /**
754       * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
755       * delayed tasks are cancelled at shutdown
756       */
757 <    public void testShutDown2() {
758 <        try {
759 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
760 <            p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
761 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
762 <            for(int i = 0; i < 5; i++)
763 <                tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
764 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
765 <            assertTrue(p1.isShutdown());
766 <            BlockingQueue q = p1.getQueue();
767 <            assertTrue(q.isEmpty());
768 <            Thread.sleep(SMALL_DELAY_MS);
769 <            assertTrue(p1.isTerminated());
770 <        }
771 <        catch(Exception ex) {
772 <            unexpectedException();
757 >    public void testShutdown2() throws InterruptedException {
758 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
759 >        p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
760 >        assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
761 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
762 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
763 >        for (int i = 0; i < tasks.length; i++)
764 >            tasks[i] = p.schedule(new NoOpRunnable(),
765 >                                  SHORT_DELAY_MS, MILLISECONDS);
766 >        BlockingQueue q = p.getQueue();
767 >        assertEquals(tasks.length, q.size());
768 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
769 >        assertTrue(p.isShutdown());
770 >        assertTrue(q.isEmpty());
771 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
772 >        assertTrue(p.isTerminated());
773 >        for (ScheduledFuture task : tasks) {
774 >            assertTrue(task.isDone());
775 >            assertTrue(task.isCancelled());
776          }
777      }
778  
613
779      /**
780       * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
781 <     * periodic tasks are not cancelled at shutdown
781 >     * periodic tasks are cancelled at shutdown
782       */
783 <    public void testShutDown3() {
784 <        try {
785 <            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
786 <            p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
787 <            ScheduledFuture task =
788 <                p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS);
789 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
790 <            assertTrue(p1.isShutdown());
791 <            BlockingQueue q = p1.getQueue();
792 <            assertTrue(q.isEmpty());
793 <            Thread.sleep(SHORT_DELAY_MS);
794 <            assertTrue(p1.isTerminated());
795 <        }
796 <        catch(Exception ex) {
797 <            unexpectedException();
798 <        }
783 >    public void testShutdown3() throws InterruptedException {
784 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
785 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
786 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
787 >        p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
788 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
789 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
790 >        long initialDelay = LONG_DELAY_MS;
791 >        ScheduledFuture task =
792 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
793 >                                  5, MILLISECONDS);
794 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
795 >        assertTrue(p.isShutdown());
796 >        assertTrue(p.getQueue().isEmpty());
797 >        assertTrue(task.isDone());
798 >        assertTrue(task.isCancelled());
799 >        joinPool(p);
800      }
801  
802      /**
803       * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
804 <     * periodic tasks are cancelled at shutdown
804 >     * periodic tasks are not cancelled at shutdown
805       */
806 <    public void testShutDown4() {
807 <        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
808 <        try {
809 <            p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
806 >    public void testShutdown4() throws InterruptedException {
807 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
808 >        final CountDownLatch counter = new CountDownLatch(2);
809 >        try {
810 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
811 >            assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
812 >            assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
813 >            final Runnable r = new CheckedRunnable() {
814 >                public void realRun() {
815 >                    counter.countDown();
816 >                }};
817              ScheduledFuture task =
818 <                p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, TimeUnit.MILLISECONDS);
818 >                p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS);
819 >            assertFalse(task.isDone());
820              assertFalse(task.isCancelled());
821 <            try { p1.shutdown(); } catch(SecurityException ok) { return; }
821 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
822              assertFalse(task.isCancelled());
823 <            assertFalse(p1.isTerminated());
824 <            assertTrue(p1.isShutdown());
825 <            Thread.sleep(SHORT_DELAY_MS);
823 >            assertFalse(p.isTerminated());
824 >            assertTrue(p.isShutdown());
825 >            assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS));
826              assertFalse(task.isCancelled());
827 <            assertTrue(task.cancel(true));
827 >            assertTrue(task.cancel(false));
828              assertTrue(task.isDone());
829 <            Thread.sleep(SHORT_DELAY_MS);
830 <            assertTrue(p1.isTerminated());
831 <        }
658 <        catch(Exception ex) {
659 <            unexpectedException();
829 >            assertTrue(task.isCancelled());
830 >            assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
831 >            assertTrue(p.isTerminated());
832          }
833 <        finally {
834 <            joinPool(p1);
833 >        finally {
834 >            joinPool(p);
835          }
836      }
837  
838      /**
839       * completed submit of callable returns result
840       */
841 <    public void testSubmitCallable() {
841 >    public void testSubmitCallable() throws Exception {
842          ExecutorService e = new ScheduledThreadPoolExecutor(2);
843          try {
844              Future<String> future = e.submit(new StringTask());
845              String result = future.get();
846              assertSame(TEST_STRING, result);
675        }
676        catch (ExecutionException ex) {
677            unexpectedException();
678        }
679        catch (InterruptedException ex) {
680            unexpectedException();
847          } finally {
848              joinPool(e);
849          }
# Line 686 | Line 852 | public class ScheduledExecutorTest exten
852      /**
853       * completed submit of runnable returns successfully
854       */
855 <    public void testSubmitRunnable() {
855 >    public void testSubmitRunnable() throws Exception {
856          ExecutorService e = new ScheduledThreadPoolExecutor(2);
857          try {
858              Future<?> future = e.submit(new NoOpRunnable());
859              future.get();
860              assertTrue(future.isDone());
695        }
696        catch (ExecutionException ex) {
697            unexpectedException();
698        }
699        catch (InterruptedException ex) {
700            unexpectedException();
861          } finally {
862              joinPool(e);
863          }
# Line 706 | Line 866 | public class ScheduledExecutorTest exten
866      /**
867       * completed submit of (runnable, result) returns result
868       */
869 <    public void testSubmitRunnable2() {
869 >    public void testSubmitRunnable2() throws Exception {
870          ExecutorService e = new ScheduledThreadPoolExecutor(2);
871          try {
872              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
873              String result = future.get();
874              assertSame(TEST_STRING, result);
715        }
716        catch (ExecutionException ex) {
717            unexpectedException();
718        }
719        catch (InterruptedException ex) {
720            unexpectedException();
875          } finally {
876              joinPool(e);
877          }
# Line 726 | Line 880 | public class ScheduledExecutorTest exten
880      /**
881       * invokeAny(null) throws NPE
882       */
883 <    public void testInvokeAny1() {
883 >    public void testInvokeAny1() throws Exception {
884          ExecutorService e = new ScheduledThreadPoolExecutor(2);
885          try {
886              e.invokeAny(null);
887 +            shouldThrow();
888          } catch (NullPointerException success) {
734        } catch(Exception ex) {
735            unexpectedException();
889          } finally {
890              joinPool(e);
891          }
# Line 741 | Line 894 | public class ScheduledExecutorTest exten
894      /**
895       * invokeAny(empty collection) throws IAE
896       */
897 <    public void testInvokeAny2() {
897 >    public void testInvokeAny2() throws Exception {
898          ExecutorService e = new ScheduledThreadPoolExecutor(2);
899          try {
900              e.invokeAny(new ArrayList<Callable<String>>());
901 +            shouldThrow();
902          } catch (IllegalArgumentException success) {
749        } catch(Exception ex) {
750            unexpectedException();
903          } finally {
904              joinPool(e);
905          }
# Line 756 | Line 908 | public class ScheduledExecutorTest exten
908      /**
909       * invokeAny(c) throws NPE if c has null elements
910       */
911 <    public void testInvokeAny3() {
911 >    public void testInvokeAny3() throws Exception {
912 >        CountDownLatch latch = new CountDownLatch(1);
913          ExecutorService e = new ScheduledThreadPoolExecutor(2);
914 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
915 +        l.add(latchAwaitingStringTask(latch));
916 +        l.add(null);
917          try {
762            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
763            l.add(new StringTask());
764            l.add(null);
918              e.invokeAny(l);
919 +            shouldThrow();
920          } catch (NullPointerException success) {
767        } catch(Exception ex) {
768            unexpectedException();
921          } finally {
922 +            latch.countDown();
923              joinPool(e);
924          }
925      }
# Line 774 | Line 927 | public class ScheduledExecutorTest exten
927      /**
928       * invokeAny(c) throws ExecutionException if no task completes
929       */
930 <    public void testInvokeAny4() {
930 >    public void testInvokeAny4() throws Exception {
931          ExecutorService e = new ScheduledThreadPoolExecutor(2);
932 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
933 +        l.add(new NPETask());
934          try {
780            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
781            l.add(new NPETask());
935              e.invokeAny(l);
936 +            shouldThrow();
937          } catch (ExecutionException success) {
938 <        } catch(Exception ex) {
785 <            unexpectedException();
938 >            assertTrue(success.getCause() instanceof NullPointerException);
939          } finally {
940              joinPool(e);
941          }
# Line 791 | Line 944 | public class ScheduledExecutorTest exten
944      /**
945       * invokeAny(c) returns result of some task
946       */
947 <    public void testInvokeAny5() {
947 >    public void testInvokeAny5() throws Exception {
948          ExecutorService e = new ScheduledThreadPoolExecutor(2);
949          try {
950 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
950 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
951              l.add(new StringTask());
952              l.add(new StringTask());
953              String result = e.invokeAny(l);
954              assertSame(TEST_STRING, result);
802        } catch (ExecutionException success) {
803        } catch(Exception ex) {
804            unexpectedException();
955          } finally {
956              joinPool(e);
957          }
# Line 810 | Line 960 | public class ScheduledExecutorTest exten
960      /**
961       * invokeAll(null) throws NPE
962       */
963 <    public void testInvokeAll1() {
963 >    public void testInvokeAll1() throws Exception {
964          ExecutorService e = new ScheduledThreadPoolExecutor(2);
965          try {
966              e.invokeAll(null);
967 +            shouldThrow();
968          } catch (NullPointerException success) {
818        } catch(Exception ex) {
819            unexpectedException();
969          } finally {
970              joinPool(e);
971          }
# Line 825 | Line 974 | public class ScheduledExecutorTest exten
974      /**
975       * invokeAll(empty collection) returns empty collection
976       */
977 <    public void testInvokeAll2() {
977 >    public void testInvokeAll2() throws Exception {
978          ExecutorService e = new ScheduledThreadPoolExecutor(2);
979          try {
980              List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
981              assertTrue(r.isEmpty());
833        } catch(Exception ex) {
834            unexpectedException();
982          } finally {
983              joinPool(e);
984          }
# Line 840 | Line 987 | public class ScheduledExecutorTest exten
987      /**
988       * invokeAll(c) throws NPE if c has null elements
989       */
990 <    public void testInvokeAll3() {
990 >    public void testInvokeAll3() throws Exception {
991          ExecutorService e = new ScheduledThreadPoolExecutor(2);
992 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
993 +        l.add(new StringTask());
994 +        l.add(null);
995          try {
846            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
847            l.add(new StringTask());
848            l.add(null);
996              e.invokeAll(l);
997 +            shouldThrow();
998          } catch (NullPointerException success) {
851        } catch(Exception ex) {
852            unexpectedException();
999          } finally {
1000              joinPool(e);
1001          }
# Line 858 | Line 1004 | public class ScheduledExecutorTest exten
1004      /**
1005       * get of invokeAll(c) throws exception on failed task
1006       */
1007 <    public void testInvokeAll4() {
1007 >    public void testInvokeAll4() throws Exception {
1008          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1009 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1010 +        l.add(new NPETask());
1011 +        List<Future<String>> futures = e.invokeAll(l);
1012 +        assertEquals(1, futures.size());
1013          try {
1014 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1015 <            l.add(new NPETask());
1016 <            List<Future<String>> result = e.invokeAll(l);
1017 <            assertEquals(1, result.size());
868 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
869 <                it.next().get();
870 <        } catch(ExecutionException success) {
871 <        } catch(Exception ex) {
872 <            unexpectedException();
1014 >            futures.get(0).get();
1015 >            shouldThrow();
1016 >        } catch (ExecutionException success) {
1017 >            assertTrue(success.getCause() instanceof NullPointerException);
1018          } finally {
1019              joinPool(e);
1020          }
# Line 878 | Line 1023 | public class ScheduledExecutorTest exten
1023      /**
1024       * invokeAll(c) returns results of all completed tasks
1025       */
1026 <    public void testInvokeAll5() {
1026 >    public void testInvokeAll5() throws Exception {
1027          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1028          try {
1029 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1029 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1030              l.add(new StringTask());
1031              l.add(new StringTask());
1032 <            List<Future<String>> result = e.invokeAll(l);
1033 <            assertEquals(2, result.size());
1034 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
1035 <                assertSame(TEST_STRING, it.next().get());
891 <        } catch (ExecutionException success) {
892 <        } catch(Exception ex) {
893 <            unexpectedException();
1032 >            List<Future<String>> futures = e.invokeAll(l);
1033 >            assertEquals(2, futures.size());
1034 >            for (Future<String> future : futures)
1035 >                assertSame(TEST_STRING, future.get());
1036          } finally {
1037              joinPool(e);
1038          }
# Line 899 | Line 1041 | public class ScheduledExecutorTest exten
1041      /**
1042       * timed invokeAny(null) throws NPE
1043       */
1044 <    public void testTimedInvokeAny1() {
1044 >    public void testTimedInvokeAny1() throws Exception {
1045          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1046          try {
1047 <            e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1047 >            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1048 >            shouldThrow();
1049          } catch (NullPointerException success) {
907        } catch(Exception ex) {
908            unexpectedException();
1050          } finally {
1051              joinPool(e);
1052          }
# Line 914 | Line 1055 | public class ScheduledExecutorTest exten
1055      /**
1056       * timed invokeAny(,,null) throws NPE
1057       */
1058 <    public void testTimedInvokeAnyNullTimeUnit() {
1058 >    public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1059          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1060 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1061 +        l.add(new StringTask());
1062          try {
920            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
921            l.add(new StringTask());
1063              e.invokeAny(l, MEDIUM_DELAY_MS, null);
1064 +            shouldThrow();
1065          } catch (NullPointerException success) {
924        } catch(Exception ex) {
925            unexpectedException();
1066          } finally {
1067              joinPool(e);
1068          }
# Line 931 | Line 1071 | public class ScheduledExecutorTest exten
1071      /**
1072       * timed invokeAny(empty collection) throws IAE
1073       */
1074 <    public void testTimedInvokeAny2() {
1074 >    public void testTimedInvokeAny2() throws Exception {
1075          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1076          try {
1077 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1077 >            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1078 >            shouldThrow();
1079          } catch (IllegalArgumentException success) {
939        } catch(Exception ex) {
940            unexpectedException();
1080          } finally {
1081              joinPool(e);
1082          }
# Line 946 | Line 1085 | public class ScheduledExecutorTest exten
1085      /**
1086       * timed invokeAny(c) throws NPE if c has null elements
1087       */
1088 <    public void testTimedInvokeAny3() {
1088 >    public void testTimedInvokeAny3() throws Exception {
1089 >        CountDownLatch latch = new CountDownLatch(1);
1090          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1091 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1092 +        l.add(latchAwaitingStringTask(latch));
1093 +        l.add(null);
1094          try {
1095 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1096 <            l.add(new StringTask());
954 <            l.add(null);
955 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1095 >            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1096 >            shouldThrow();
1097          } catch (NullPointerException success) {
957        } catch(Exception ex) {
958            ex.printStackTrace();
959            unexpectedException();
1098          } finally {
1099 +            latch.countDown();
1100              joinPool(e);
1101          }
1102      }
# Line 965 | Line 1104 | public class ScheduledExecutorTest exten
1104      /**
1105       * timed invokeAny(c) throws ExecutionException if no task completes
1106       */
1107 <    public void testTimedInvokeAny4() {
1107 >    public void testTimedInvokeAny4() throws Exception {
1108          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1109 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1110 +        l.add(new NPETask());
1111          try {
1112 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1113 <            l.add(new NPETask());
1114 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1115 <        } catch(ExecutionException success) {
975 <        } catch(Exception ex) {
976 <            unexpectedException();
1112 >            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1113 >            shouldThrow();
1114 >        } catch (ExecutionException success) {
1115 >            assertTrue(success.getCause() instanceof NullPointerException);
1116          } finally {
1117              joinPool(e);
1118          }
# Line 982 | Line 1121 | public class ScheduledExecutorTest exten
1121      /**
1122       * timed invokeAny(c) returns result of some task
1123       */
1124 <    public void testTimedInvokeAny5() {
1124 >    public void testTimedInvokeAny5() throws Exception {
1125          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1126          try {
1127 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1127 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1128              l.add(new StringTask());
1129              l.add(new StringTask());
1130 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1130 >            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1131              assertSame(TEST_STRING, result);
993        } catch (ExecutionException success) {
994        } catch(Exception ex) {
995            unexpectedException();
1132          } finally {
1133              joinPool(e);
1134          }
# Line 1001 | Line 1137 | public class ScheduledExecutorTest exten
1137      /**
1138       * timed invokeAll(null) throws NPE
1139       */
1140 <    public void testTimedInvokeAll1() {
1140 >    public void testTimedInvokeAll1() throws Exception {
1141          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1142          try {
1143 <            e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1143 >            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1144 >            shouldThrow();
1145          } catch (NullPointerException success) {
1009        } catch(Exception ex) {
1010            unexpectedException();
1146          } finally {
1147              joinPool(e);
1148          }
# Line 1016 | Line 1151 | public class ScheduledExecutorTest exten
1151      /**
1152       * timed invokeAll(,,null) throws NPE
1153       */
1154 <    public void testTimedInvokeAllNullTimeUnit() {
1154 >    public void testTimedInvokeAllNullTimeUnit() throws Exception {
1155          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1156 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1157 +        l.add(new StringTask());
1158          try {
1022            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1023            l.add(new StringTask());
1159              e.invokeAll(l, MEDIUM_DELAY_MS, null);
1160 +            shouldThrow();
1161          } catch (NullPointerException success) {
1026        } catch(Exception ex) {
1027            unexpectedException();
1162          } finally {
1163              joinPool(e);
1164          }
# Line 1033 | Line 1167 | public class ScheduledExecutorTest exten
1167      /**
1168       * timed invokeAll(empty collection) returns empty collection
1169       */
1170 <    public void testTimedInvokeAll2() {
1170 >    public void testTimedInvokeAll2() throws Exception {
1171          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1172          try {
1173 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1173 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1174              assertTrue(r.isEmpty());
1041        } catch(Exception ex) {
1042            unexpectedException();
1175          } finally {
1176              joinPool(e);
1177          }
# Line 1048 | Line 1180 | public class ScheduledExecutorTest exten
1180      /**
1181       * timed invokeAll(c) throws NPE if c has null elements
1182       */
1183 <    public void testTimedInvokeAll3() {
1183 >    public void testTimedInvokeAll3() throws Exception {
1184          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1185 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1186 +        l.add(new StringTask());
1187 +        l.add(null);
1188          try {
1189 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1190 <            l.add(new StringTask());
1056 <            l.add(null);
1057 <            e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1189 >            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1190 >            shouldThrow();
1191          } catch (NullPointerException success) {
1059        } catch(Exception ex) {
1060            unexpectedException();
1192          } finally {
1193              joinPool(e);
1194          }
# Line 1066 | Line 1197 | public class ScheduledExecutorTest exten
1197      /**
1198       * get of element of invokeAll(c) throws exception on failed task
1199       */
1200 <    public void testTimedInvokeAll4() {
1200 >    public void testTimedInvokeAll4() throws Exception {
1201          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1202 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
1203 +        l.add(new NPETask());
1204 +        List<Future<String>> futures =
1205 +            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1206 +        assertEquals(1, futures.size());
1207          try {
1208 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1209 <            l.add(new NPETask());
1210 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1211 <            assertEquals(1, result.size());
1076 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
1077 <                it.next().get();
1078 <        } catch(ExecutionException success) {
1079 <        } catch(Exception ex) {
1080 <            unexpectedException();
1208 >            futures.get(0).get();
1209 >            shouldThrow();
1210 >        } catch (ExecutionException success) {
1211 >            assertTrue(success.getCause() instanceof NullPointerException);
1212          } finally {
1213              joinPool(e);
1214          }
# Line 1086 | Line 1217 | public class ScheduledExecutorTest exten
1217      /**
1218       * timed invokeAll(c) returns results of all completed tasks
1219       */
1220 <    public void testTimedInvokeAll5() {
1220 >    public void testTimedInvokeAll5() throws Exception {
1221          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1222          try {
1223 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1223 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1224              l.add(new StringTask());
1225              l.add(new StringTask());
1226 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
1227 <            assertEquals(2, result.size());
1228 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
1229 <                assertSame(TEST_STRING, it.next().get());
1230 <        } catch (ExecutionException success) {
1100 <        } catch(Exception ex) {
1101 <            unexpectedException();
1226 >            List<Future<String>> futures =
1227 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1228 >            assertEquals(2, futures.size());
1229 >            for (Future<String> future : futures)
1230 >                assertSame(TEST_STRING, future.get());
1231          } finally {
1232              joinPool(e);
1233          }
# Line 1107 | Line 1236 | public class ScheduledExecutorTest exten
1236      /**
1237       * timed invokeAll(c) cancels tasks not completed by timeout
1238       */
1239 <    public void testTimedInvokeAll6() {
1239 >    public void testTimedInvokeAll6() throws Exception {
1240          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1241          try {
1242 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
1243 <            l.add(new StringTask());
1244 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1245 <            l.add(new StringTask());
1246 <            List<Future<String>> result = e.invokeAll(l, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
1247 <            assertEquals(3, result.size());
1248 <            Iterator<Future<String>> it = result.iterator();
1249 <            Future<String> f1 = it.next();
1250 <            Future<String> f2 = it.next();
1251 <            Future<String> f3 = it.next();
1252 <            assertTrue(f1.isDone());
1253 <            assertTrue(f2.isDone());
1254 <            assertTrue(f3.isDone());
1255 <            assertFalse(f1.isCancelled());
1256 <            assertTrue(f2.isCancelled());
1257 <        } catch(Exception ex) {
1258 <            unexpectedException();
1242 >            for (long timeout = timeoutMillis();;) {
1243 >                List<Callable<String>> tasks = new ArrayList<>();
1244 >                tasks.add(new StringTask("0"));
1245 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1246 >                tasks.add(new StringTask("2"));
1247 >                long startTime = System.nanoTime();
1248 >                List<Future<String>> futures =
1249 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1250 >                assertEquals(tasks.size(), futures.size());
1251 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1252 >                for (Future future : futures)
1253 >                    assertTrue(future.isDone());
1254 >                assertTrue(futures.get(1).isCancelled());
1255 >                try {
1256 >                    assertEquals("0", futures.get(0).get());
1257 >                    assertEquals("2", futures.get(2).get());
1258 >                    break;
1259 >                } catch (CancellationException retryWithLongerTimeout) {
1260 >                    timeout *= 2;
1261 >                    if (timeout >= LONG_DELAY_MS / 2)
1262 >                        fail("expected exactly one task to be cancelled");
1263 >                }
1264 >            }
1265          } finally {
1266              joinPool(e);
1267          }
1268      }
1269  
1135
1270   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines