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.3 by dl, Mon Sep 8 12:12:42 2003 UTC vs.
Revision 1.44 by jsr166, Sat May 28 15:33:20 2011 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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 static java.util.concurrent.TimeUnit.MILLISECONDS;
13 + import java.util.concurrent.atomic.*;
14  
15 < public class ScheduledExecutorTest extends TestCase{
13 <    
14 <    boolean flag = false;
15 <
15 > public class ScheduledExecutorTest extends JSR166TestCase {
16      public static void main(String[] args) {
17 <        junit.textui.TestRunner.run (suite());  
17 >        junit.textui.TestRunner.run(suite());
18      }
19    
20
19      public static Test suite() {
20 <        return new TestSuite(ScheduledExecutorTest.class);
20 >        return new TestSuite(ScheduledExecutorTest.class);
21      }
22  
23 <    private static long SHORT_DELAY_MS = 100;
24 <    private static long MEDIUM_DELAY_MS = 1000;
25 <    private static long LONG_DELAY_MS = 10000;
26 <
27 <    static class MyRunnable implements Runnable {
28 <        volatile boolean waiting = true;
29 <        volatile boolean done = false;
30 <        public void run(){
31 <            try{
32 <                Thread.sleep(SHORT_DELAY_MS);
33 <                waiting = false;
34 <                done = true;
35 <            } catch(Exception e){
36 <            }
23 >    /**
24 >     * execute successfully executes a runnable
25 >     */
26 >    public void testExecute() throws InterruptedException {
27 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
28 >        final CountDownLatch done = new CountDownLatch(1);
29 >        final Runnable task = new CheckedRunnable() {
30 >            public void realRun() {
31 >                done.countDown();
32 >            }};
33 >        try {
34 >            p.execute(task);
35 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
36 >        } finally {
37 >            joinPool(p);
38          }
39      }
40  
41 <    static class MyCallable implements Callable {
42 <        volatile boolean waiting = true;
43 <        volatile boolean done = false;
44 <        public Object call(){
45 <            try{
46 <                Thread.sleep(SHORT_DELAY_MS);
47 <                waiting = false;
48 <                done = true;
49 <            }catch(Exception e){}
50 <            return Boolean.TRUE;
41 >    /**
42 >     * delayed schedule of callable successfully executes after delay
43 >     */
44 >    public void testSchedule1() throws Exception {
45 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
46 >        final long startTime = System.nanoTime();
47 >        final CountDownLatch done = new CountDownLatch(1);
48 >        try {
49 >            Callable task = new CheckedCallable<Boolean>() {
50 >                public Boolean realCall() {
51 >                    done.countDown();
52 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
53 >                    return Boolean.TRUE;
54 >                }};
55 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
56 >            assertSame(Boolean.TRUE, f.get());
57 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
58 >            assertTrue(done.await(0L, MILLISECONDS));
59 >        } finally {
60 >            joinPool(p);
61          }
62      }
63  
64 <    public Runnable newRunnable(){
65 <        return new Runnable(){
66 <                public void run(){
67 <                    try{Thread.sleep(SHORT_DELAY_MS);
68 <                    } catch(Exception e){
69 <                    }
70 <                }
71 <            };
72 <    }
73 <
74 <    public Runnable newNoopRunnable() {
75 <        return new Runnable(){
76 <                public void run(){
77 <                }
78 <            };
64 >    /**
65 >     * delayed schedule of runnable successfully executes after delay
66 >     */
67 >    public void testSchedule3() throws Exception {
68 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
69 >        final long startTime = System.nanoTime();
70 >        final CountDownLatch done = new CountDownLatch(1);
71 >        try {
72 >            Runnable task = new CheckedRunnable() {
73 >                public void realRun() {
74 >                    done.countDown();
75 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76 >                }};
77 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
78 >            await(done);
79 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
80 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
81 >        } finally {
82 >            joinPool(p);
83 >        }
84      }
85  
86      /**
87 <     *  Test to verify execute successfully runs the given Runnable
88 <     */
89 <    public void testExecute(){
90 <        try{
91 <            MyRunnable runnable =new MyRunnable();
92 <            ScheduledExecutor one = new ScheduledExecutor(1);
93 <            one.execute(runnable);
94 <            Thread.sleep(SHORT_DELAY_MS/2);
95 <            assertTrue(runnable.waiting);
96 <            one.shutdown();
97 <            try{
98 <                Thread.sleep(MEDIUM_DELAY_MS);
99 <            } catch(InterruptedException e){
100 <                fail("unexpected exception");
101 <            }
102 <            assertFalse(runnable.waiting);
103 <            assertTrue(runnable.done);
104 <            one.shutdown();
105 <        }
106 <        catch(Exception e){
93 <            fail("unexpected exception");
87 >     * scheduleAtFixedRate executes runnable after given initial delay
88 >     */
89 >    public void testSchedule4() throws Exception {
90 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
91 >        final long startTime = System.nanoTime();
92 >        final CountDownLatch done = new CountDownLatch(1);
93 >        try {
94 >            Runnable task = new CheckedRunnable() {
95 >                public void realRun() {
96 >                    done.countDown();
97 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
98 >                }};
99 >            ScheduledFuture f =
100 >                p.scheduleAtFixedRate(task, timeoutMillis(),
101 >                                      LONG_DELAY_MS, MILLISECONDS);
102 >            await(done);
103 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
104 >            f.cancel(true);
105 >        } finally {
106 >            joinPool(p);
107          }
108      }
109  
110      /**
111 <     *  Test to verify schedule successfully runs the given Callable.
99 <     *  The waiting flag shows that the Callable is not started until
100 <     *  immediately.
111 >     * scheduleWithFixedDelay executes runnable after given initial delay
112       */
113 <    public void testSchedule1(){
114 <        try{
115 <            MyCallable callable = new MyCallable();
116 <            ScheduledExecutor one = new ScheduledExecutor(1);
117 <            Future f = one.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
118 <            assertTrue(callable.waiting);
119 <            Thread.sleep(MEDIUM_DELAY_MS);
120 <            assertTrue(callable.done);
121 <            assertEquals(Boolean.TRUE, f.get());
122 <            one.shutdown();
123 <        }catch(RejectedExecutionException e){}
124 <        catch(Exception e){
125 <            fail("unexpected exception");
113 >    public void testSchedule5() throws Exception {
114 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
115 >        final long startTime = System.nanoTime();
116 >        final CountDownLatch done = new CountDownLatch(1);
117 >        try {
118 >            Runnable task = new CheckedRunnable() {
119 >                public void realRun() {
120 >                    done.countDown();
121 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
122 >                }};
123 >            ScheduledFuture f =
124 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
125 >                                         LONG_DELAY_MS, MILLISECONDS);
126 >            await(done);
127 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
128 >            f.cancel(true);
129 >        } finally {
130 >            joinPool(p);
131          }
132      }
133  
134 +    static class RunnableCounter implements Runnable {
135 +        AtomicInteger count = new AtomicInteger(0);
136 +        public void run() { count.getAndIncrement(); }
137 +    }
138 +
139      /**
140 <     *  Another version of schedule, only using Runnable instead of Callable
140 >     * scheduleAtFixedRate executes series of tasks at given rate
141       */
142 <    public void testSchedule3(){
143 <        try{
144 <            MyRunnable runnable = new MyRunnable();
145 <            ScheduledExecutor one = new ScheduledExecutor(1);
146 <            one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
147 <            Thread.sleep(SHORT_DELAY_MS/2);
148 <            assertTrue(runnable.waiting);
149 <            Thread.sleep(MEDIUM_DELAY_MS);
150 <            assertTrue(runnable.done);
151 <            one.shutdown();
152 <        } catch(Exception e){
153 <            fail("unexpected exception");
154 <        }
142 >    public void testFixedRateSequence() throws InterruptedException {
143 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
144 >        RunnableCounter counter = new RunnableCounter();
145 >        ScheduledFuture h =
146 >            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
147 >        delay(SMALL_DELAY_MS);
148 >        h.cancel(true);
149 >        int c = counter.count.get();
150 >        // By time scaling conventions, we must have at least
151 >        // an execution per SHORT delay, but no more than one SHORT more
152 >        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
153 >        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
154 >        joinPool(p);
155      }
156 <    
156 >
157      /**
158 <     *  The final version of schedule, using both long, TimeUnit and Runnable
158 >     * scheduleWithFixedDelay executes series of tasks with given period
159       */
160 <    public void testSchedule4(){
161 <        try{
162 <            MyRunnable runnable = new MyRunnable();
163 <            ScheduledExecutor one = new ScheduledExecutor(1);
164 <            one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
165 <            //      Thread.sleep(505);
166 <            assertTrue(runnable.waiting);
167 <            Thread.sleep(MEDIUM_DELAY_MS);
168 <            assertTrue(runnable.done);
169 <            one.shutdown();
170 <        } catch(Exception e){
150 <            fail("unexpected exception");
151 <        }
160 >    public void testFixedDelaySequence() throws InterruptedException {
161 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
162 >        RunnableCounter counter = new RunnableCounter();
163 >        ScheduledFuture h =
164 >            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
165 >        delay(SMALL_DELAY_MS);
166 >        h.cancel(true);
167 >        int c = counter.count.get();
168 >        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
169 >        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
170 >        joinPool(p);
171      }
153    
154  
155    // exception tests
172  
173      /**
174 <     *  Test to verify schedule(Runnable, long) throws RejectedExecutionException
159 <     *  This occurs on an attempt to schedule a task on a shutdown executor
174 >     * execute(null) throws NPE
175       */
176 <    public void testSchedule1_RejectedExecutionException(){
177 <        try{
178 <            ScheduledExecutor se = new ScheduledExecutor(1);
179 <            se.shutdown();
180 <            se.schedule(new Runnable(){
181 <                    public void run(){}
182 <                }, 10000, TimeUnit.MILLISECONDS);
183 <            fail("shoud throw");
184 <        }catch(RejectedExecutionException e){}    
176 >    public void testExecuteNull() throws InterruptedException {
177 >        ScheduledThreadPoolExecutor se = null;
178 >        try {
179 >            se = new ScheduledThreadPoolExecutor(1);
180 >            se.execute(null);
181 >            shouldThrow();
182 >        } catch (NullPointerException success) {}
183 >
184 >        joinPool(se);
185      }
186  
187      /**
188 <     *  Test to verify schedule(Callable, long, TimeUnit) throws RejectedExecutionException
174 <     *  This occurs on an attempt to schedule a task on a shutdown executor
188 >     * schedule(null) throws NPE
189       */
190 <    public void testSchedule2_RejectedExecutionException(){
191 <        try{
192 <            ScheduledExecutor se = new ScheduledExecutor(1);
193 <            se.shutdown();
194 <            se.schedule(new Callable(){
195 <                    public Object call(){
196 <                        return Boolean.TRUE;
197 <                    }
184 <                }, (long)100, TimeUnit.SECONDS);
185 <            fail("should throw");
186 <        }catch(RejectedExecutionException e){}    
190 >    public void testScheduleNull() throws InterruptedException {
191 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
192 >        try {
193 >            TrackedCallable callable = null;
194 >            Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
195 >            shouldThrow();
196 >        } catch (NullPointerException success) {}
197 >        joinPool(se);
198      }
199  
200      /**
201 <     *  Test to verify schedule(Callable, long) throws RejectedExecutionException
202 <     *  This occurs on an attempt to schedule a task on a shutdown executor
203 <     */
204 <     public void testSchedule3_RejectedExecutionException(){
205 <        try{
195 <            ScheduledExecutor se = new ScheduledExecutor(1);
201 >     * execute throws RejectedExecutionException if shutdown
202 >     */
203 >    public void testSchedule1_RejectedExecutionException() throws InterruptedException {
204 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
205 >        try {
206              se.shutdown();
207 <            se.schedule(new Callable(){
208 <                    public Object call(){
209 <                        return Boolean.TRUE;
210 <                    }
211 <                },  10000, TimeUnit.MILLISECONDS);
212 <            fail("should throw");
213 <        }catch(RejectedExecutionException e){}    
207 >            se.schedule(new NoOpRunnable(),
208 >                        MEDIUM_DELAY_MS, MILLISECONDS);
209 >            shouldThrow();
210 >        } catch (RejectedExecutionException success) {
211 >        } catch (SecurityException ok) {
212 >        }
213 >
214 >        joinPool(se);
215      }
216  
217      /**
218 <     *  Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws
219 <     *  RejectedExecutionException.
220 <     *  This occurs on an attempt to schedule a task on a shutdown executor
221 <     */
222 <    public void testScheduleAtFixedRate1_RejectedExecutionException(){
212 <        try{
213 <            ScheduledExecutor se = new ScheduledExecutor(1);
214 <            se.shutdown();
215 <            se.scheduleAtFixedRate(new Runnable(){
216 <                    public void run(){}
217 <                }, 100, 100, TimeUnit.SECONDS);
218 <            fail("should throw");
219 <        }catch(RejectedExecutionException e){}    
220 <    }
221 <    
222 <    /**
223 <     *  Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws
224 <     *  RejectedExecutionException.
225 <     *  This occurs on an attempt to schedule a task on a shutdown executor
226 <     */
227 <    public void testScheduleAtFixedRate2_RejectedExecutionException(){
228 <        try{
229 <            ScheduledExecutor se = new ScheduledExecutor(1);
218 >     * schedule throws RejectedExecutionException if shutdown
219 >     */
220 >    public void testSchedule2_RejectedExecutionException() throws InterruptedException {
221 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
222 >        try {
223              se.shutdown();
224 <            se.scheduleAtFixedRate(new Runnable(){
225 <                    public void run(){}
226 <                },  1, 100, TimeUnit.SECONDS);
227 <            fail("should throw");
228 <        }catch(RejectedExecutionException e){}    
224 >            se.schedule(new NoOpCallable(),
225 >                        MEDIUM_DELAY_MS, MILLISECONDS);
226 >            shouldThrow();
227 >        } catch (RejectedExecutionException success) {
228 >        } catch (SecurityException ok) {
229 >        }
230 >        joinPool(se);
231      }
232  
233      /**
234 <     *  Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws
240 <     *  RejectedExecutionException.
241 <     *  This occurs on an attempt to schedule a task on a shutdown executor
234 >     * schedule callable throws RejectedExecutionException if shutdown
235       */
236 <    public void testScheduleWithFixedDelay1_RejectedExecutionException(){
237 <        try{
238 <            ScheduledExecutor se = new ScheduledExecutor(1);
236 >    public void testSchedule3_RejectedExecutionException() throws InterruptedException {
237 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
238 >        try {
239              se.shutdown();
240 <            se.scheduleWithFixedDelay(new Runnable(){
241 <                    public void run(){}
242 <                }, 100, 100, TimeUnit.SECONDS);
243 <            fail("should throw");
244 <        }catch(RejectedExecutionException e){}    
240 >            se.schedule(new NoOpCallable(),
241 >                        MEDIUM_DELAY_MS, MILLISECONDS);
242 >            shouldThrow();
243 >        } catch (RejectedExecutionException success) {
244 >        } catch (SecurityException ok) {
245 >        }
246 >        joinPool(se);
247      }
248  
249      /**
250 <     *  Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws
256 <     *  RejectedExecutionException.
257 <     *  This occurs on an attempt to schedule a task on a shutdown executor
250 >     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
251       */
252 <     public void testScheduleWithFixedDelay2_RejectedExecutionException(){
253 <        try{
254 <            ScheduledExecutor se = new ScheduledExecutor(1);
252 >    public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
253 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
254 >        try {
255              se.shutdown();
256 <            se.scheduleWithFixedDelay(new Runnable(){
257 <                    public void run(){}
258 <                },  1, 100, TimeUnit.SECONDS);
259 <            fail("should throw");
260 <        }catch(RejectedExecutionException e){}    
256 >            se.scheduleAtFixedRate(new NoOpRunnable(),
257 >                                   MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
258 >            shouldThrow();
259 >        } catch (RejectedExecutionException success) {
260 >        } catch (SecurityException ok) {
261 >        }
262 >        joinPool(se);
263      }
264  
265      /**
266 <     *  Test to verify execute throws RejectedExecutionException
272 <     *  This occurs on an attempt to schedule a task on a shutdown executor
266 >     * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
267       */
268 <    public void testExecute_RejectedExecutionException(){
269 <        try{
270 <            ScheduledExecutor se = new ScheduledExecutor(1);
268 >    public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
269 >        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
270 >        try {
271              se.shutdown();
272 <            se.execute(new Runnable(){
273 <                    public void run(){}
274 <                });
275 <            fail("should throw");
276 <        }catch(RejectedExecutionException e){}    
272 >            se.scheduleWithFixedDelay(new NoOpRunnable(),
273 >                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
274 >            shouldThrow();
275 >        } catch (RejectedExecutionException success) {
276 >        } catch (SecurityException ok) {
277 >        }
278 >        joinPool(se);
279      }
280  
285
286
281      /**
282 <     *  Test to verify getActiveCount gives correct values
282 >     * getActiveCount increases but doesn't overestimate, when a
283 >     * thread becomes active
284       */
285 <    public void testGetActiveCount(){
286 <        ScheduledExecutor two = new ScheduledExecutor(2);
285 >    public void testGetActiveCount() throws InterruptedException {
286 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
287 >        final CountDownLatch threadStarted = new CountDownLatch(1);
288 >        final CountDownLatch done = new CountDownLatch(1);
289          try {
290 <            assertEquals(0, two.getActiveCount());
291 <            two.execute(newRunnable());
292 <            try{
293 <                Thread.sleep(SHORT_DELAY_MS/2);
294 <            } catch(Exception e){
295 <                fail("unexpected exception");
296 <            }
297 <            assertEquals(1, two.getActiveCount());
290 >            assertEquals(0, p.getActiveCount());
291 >            p.execute(new CheckedRunnable() {
292 >                public void realRun() throws InterruptedException {
293 >                    threadStarted.countDown();
294 >                    assertEquals(1, p.getActiveCount());
295 >                    done.await();
296 >                }});
297 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
298 >            assertEquals(1, p.getActiveCount());
299          } finally {
300 <            two.shutdown();
300 >            done.countDown();
301 >            joinPool(p);
302          }
303      }
304 <    
304 >
305      /**
306 <     *  Test to verify getCompleteTaskCount gives correct values
306 >     * getCompletedTaskCount increases, but doesn't overestimate,
307 >     * when tasks complete
308       */
309 <    public void testGetCompletedTaskCount(){
310 <        ScheduledExecutor two = new ScheduledExecutor(2);
309 >    public void testGetCompletedTaskCount() throws InterruptedException {
310 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
311 >        final CountDownLatch threadStarted = new CountDownLatch(1);
312 >        final CountDownLatch threadProceed = new CountDownLatch(1);
313 >        final CountDownLatch threadDone = new CountDownLatch(1);
314          try {
315 <            assertEquals(0, two.getCompletedTaskCount());
316 <            two.execute(newRunnable());
317 <            try{
318 <                Thread.sleep(MEDIUM_DELAY_MS/2);
319 <            } catch(Exception e){
320 <                fail("unexpected exception");
315 >            assertEquals(0, p.getCompletedTaskCount());
316 >            p.execute(new CheckedRunnable() {
317 >                public void realRun() throws InterruptedException {
318 >                    threadStarted.countDown();
319 >                    assertEquals(0, p.getCompletedTaskCount());
320 >                    threadProceed.await();
321 >                    threadDone.countDown();
322 >                }});
323 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
324 >            assertEquals(0, p.getCompletedTaskCount());
325 >            threadProceed.countDown();
326 >            threadDone.await();
327 >            long startTime = System.nanoTime();
328 >            while (p.getCompletedTaskCount() != 1) {
329 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
330 >                    fail("timed out");
331 >                Thread.yield();
332              }
319            assertEquals(1, two.getCompletedTaskCount());
333          } finally {
334 <            two.shutdown();
334 >            joinPool(p);
335          }
336      }
337 <    
337 >
338 >    /**
339 >     * getCorePoolSize returns size given in constructor if not otherwise set
340 >     */
341 >    public void testGetCorePoolSize() throws InterruptedException {
342 >        ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
343 >        assertEquals(1, p.getCorePoolSize());
344 >        joinPool(p);
345 >    }
346 >
347      /**
348 <     *  Test to verify getCorePoolSize gives correct values
348 >     * getLargestPoolSize increases, but doesn't overestimate, when
349 >     * multiple threads active
350       */
351 <    public void testGetCorePoolSize(){
352 <        ScheduledExecutor one = new ScheduledExecutor(1);
351 >    public void testGetLargestPoolSize() throws InterruptedException {
352 >        final int THREADS = 3;
353 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
354 >        final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
355 >        final CountDownLatch done = new CountDownLatch(1);
356          try {
357 <            assertEquals(1, one.getCorePoolSize());
357 >            assertEquals(0, p.getLargestPoolSize());
358 >            for (int i = 0; i < THREADS; i++)
359 >                p.execute(new CheckedRunnable() {
360 >                    public void realRun() throws InterruptedException {
361 >                        threadsStarted.countDown();
362 >                        done.await();
363 >                        assertEquals(THREADS, p.getLargestPoolSize());
364 >                    }});
365 >            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
366 >            assertEquals(THREADS, p.getLargestPoolSize());
367          } finally {
368 <            one.shutdown();
368 >            done.countDown();
369 >            joinPool(p);
370 >            assertEquals(THREADS, p.getLargestPoolSize());
371          }
372      }
373 <    
373 >
374      /**
375 <     *  Test to verify getLargestPoolSize gives correct values
375 >     * getPoolSize increases, but doesn't overestimate, when threads
376 >     * become active
377       */
378 <    public void testGetLargestPoolSize(){
379 <        ScheduledExecutor two = new ScheduledExecutor(2);
378 >    public void testGetPoolSize() throws InterruptedException {
379 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
380 >        final CountDownLatch threadStarted = new CountDownLatch(1);
381 >        final CountDownLatch done = new CountDownLatch(1);
382          try {
383 <            assertEquals(0, two.getLargestPoolSize());
384 <            two.execute(newRunnable());
385 <            two.execute(newRunnable());
386 <            try{
387 <                Thread.sleep(SHORT_DELAY_MS/2);
388 <            } catch(Exception e){
389 <                fail("unexpected exception");
390 <            }
391 <            assertEquals(2, two.getLargestPoolSize());
383 >            assertEquals(0, p.getPoolSize());
384 >            p.execute(new CheckedRunnable() {
385 >                public void realRun() throws InterruptedException {
386 >                    threadStarted.countDown();
387 >                    assertEquals(1, p.getPoolSize());
388 >                    done.await();
389 >                }});
390 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
391 >            assertEquals(1, p.getPoolSize());
392          } finally {
393 <            two.shutdown();
393 >            done.countDown();
394 >            joinPool(p);
395          }
396      }
397 <    
397 >
398      /**
399 <     *  Test to verify getPoolSize gives correct values
399 >     * getTaskCount increases, but doesn't overestimate, when tasks
400 >     * submitted
401       */
402 <    public void testGetPoolSize(){
403 <        ScheduledExecutor one = new ScheduledExecutor(1);
404 <        try {
405 <            assertEquals(0, one.getPoolSize());
406 <            one.execute(newRunnable());
407 <            assertEquals(1, one.getPoolSize());
402 >    public void testGetTaskCount() throws InterruptedException {
403 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
404 >        final CountDownLatch threadStarted = new CountDownLatch(1);
405 >        final CountDownLatch done = new CountDownLatch(1);
406 >        final int TASKS = 5;
407 >        try {
408 >            assertEquals(0, p.getTaskCount());
409 >            for (int i = 0; i < TASKS; i++)
410 >                p.execute(new CheckedRunnable() {
411 >                    public void realRun() throws InterruptedException {
412 >                        threadStarted.countDown();
413 >                        done.await();
414 >                    }});
415 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
416 >            assertEquals(TASKS, p.getTaskCount());
417          } finally {
418 <            one.shutdown();
418 >            done.countDown();
419 >            joinPool(p);
420          }
421      }
422 <    
422 >
423 >    /**
424 >     * getThreadFactory returns factory in constructor if not set
425 >     */
426 >    public void testGetThreadFactory() throws InterruptedException {
427 >        ThreadFactory tf = new SimpleThreadFactory();
428 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
429 >        assertSame(tf, p.getThreadFactory());
430 >        joinPool(p);
431 >    }
432 >
433 >    /**
434 >     * setThreadFactory sets the thread factory returned by getThreadFactory
435 >     */
436 >    public void testSetThreadFactory() throws InterruptedException {
437 >        ThreadFactory tf = new SimpleThreadFactory();
438 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
439 >        p.setThreadFactory(tf);
440 >        assertSame(tf, p.getThreadFactory());
441 >        joinPool(p);
442 >    }
443 >
444      /**
445 <     *  Test to verify getTaskCount gives correct values
445 >     * setThreadFactory(null) throws NPE
446       */
447 <    public void testGetTaskCount(){
448 <        ScheduledExecutor one = new ScheduledExecutor(1);
447 >    public void testSetThreadFactoryNull() throws InterruptedException {
448 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
449          try {
450 <            assertEquals(0, one.getTaskCount());
451 <            for(int i = 0; i < 5; i++)
452 <                one.execute(newRunnable());
380 <            try{
381 <                Thread.sleep(SHORT_DELAY_MS/2);
382 <            } catch(Exception e){
383 <                fail("unexpected exception");
384 <            }
385 <            assertEquals(5, one.getTaskCount());
450 >            p.setThreadFactory(null);
451 >            shouldThrow();
452 >        } catch (NullPointerException success) {
453          } finally {
454 <            one.shutdown();
454 >            joinPool(p);
455          }
456      }
457 <    
457 >
458      /**
459 <     *  Test to verify isShutDown gives correct values
459 >     * isShutdown is false before shutdown, true after
460       */
461 <    public void testIsShutdown(){
462 <        
463 <        ScheduledExecutor one = new ScheduledExecutor(1);
461 >    public void testIsShutdown() {
462 >
463 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
464          try {
465 <            assertFalse(one.isShutdown());
465 >            assertFalse(p.isShutdown());
466          }
467          finally {
468 <            one.shutdown();
468 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
469 >        }
470 >        assertTrue(p.isShutdown());
471 >    }
472 >
473 >    /**
474 >     * isTerminated is false before termination, true after
475 >     */
476 >    public void testIsTerminated() throws InterruptedException {
477 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
478 >        final CountDownLatch threadStarted = new CountDownLatch(1);
479 >        final CountDownLatch done = new CountDownLatch(1);
480 >        assertFalse(p.isTerminated());
481 >        try {
482 >            p.execute(new CheckedRunnable() {
483 >                public void realRun() throws InterruptedException {
484 >                    assertFalse(p.isTerminated());
485 >                    threadStarted.countDown();
486 >                    done.await();
487 >                }});
488 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
489 >            assertFalse(p.isTerminating());
490 >            done.countDown();
491 >        } finally {
492 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
493          }
494 <        assertTrue(one.isShutdown());
494 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
495 >        assertTrue(p.isTerminated());
496      }
497  
406        
498      /**
499 <     *  Test to verify isTerminated gives correct values
409 <     *  Makes sure termination does not take an innapropriate
410 <     *  amount of time
499 >     * isTerminating is not true when running or when terminated
500       */
501 <    public void testIsTerminated(){
502 <        ScheduledExecutor one = new ScheduledExecutor(1);
501 >    public void testIsTerminating() throws InterruptedException {
502 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
503 >        final CountDownLatch threadStarted = new CountDownLatch(1);
504 >        final CountDownLatch done = new CountDownLatch(1);
505          try {
506 <            one.execute(newRunnable());
506 >            assertFalse(p.isTerminating());
507 >            p.execute(new CheckedRunnable() {
508 >                public void realRun() throws InterruptedException {
509 >                    assertFalse(p.isTerminating());
510 >                    threadStarted.countDown();
511 >                    done.await();
512 >                }});
513 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
514 >            assertFalse(p.isTerminating());
515 >            done.countDown();
516          } finally {
517 <            one.shutdown();
517 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
518          }
519 <        boolean flag = false;
520 <        try{
521 <            flag = one.awaitTermination(10, TimeUnit.SECONDS);
422 <        } catch(Exception e){
423 <            fail("unexpected exception");
424 <        }      
425 <        assertTrue(one.isTerminated());
426 <        if(!flag)
427 <            fail("ThreadPoolExecutor - thread pool did not terminate within suitable timeframe");
519 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
520 >        assertTrue(p.isTerminated());
521 >        assertFalse(p.isTerminating());
522      }
523  
524      /**
525 <     *  Test to verify that purge correctly removes cancelled tasks
432 <     *  from the queue
525 >     * getQueue returns the work queue, which contains queued tasks
526       */
527 <    public void testPurge(){
528 <        ScheduledExecutor one = new ScheduledExecutor(1);
527 >    public void testGetQueue() throws InterruptedException {
528 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
529 >        final CountDownLatch threadStarted = new CountDownLatch(1);
530 >        final CountDownLatch done = new CountDownLatch(1);
531          try {
532 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
533 <            for(int i = 0; i < 5; i++){
534 <                tasks[i] = one.schedule(newRunnable(), 1, TimeUnit.MILLISECONDS);
532 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
533 >            for (int i = 0; i < tasks.length; i++) {
534 >                Runnable r = new CheckedRunnable() {
535 >                    public void realRun() throws InterruptedException {
536 >                        threadStarted.countDown();
537 >                        done.await();
538 >                    }};
539 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
540              }
541 <            int max = 5;
541 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
542 >            BlockingQueue<Runnable> q = p.getQueue();
543 >            assertTrue(q.contains(tasks[tasks.length - 1]));
544 >            assertFalse(q.contains(tasks[0]));
545 >        } finally {
546 >            done.countDown();
547 >            joinPool(p);
548 >        }
549 >    }
550 >
551 >    /**
552 >     * remove(task) removes queued task, and fails to remove active task
553 >     */
554 >    public void testRemove() throws InterruptedException {
555 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
556 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
557 >        final CountDownLatch threadStarted = new CountDownLatch(1);
558 >        final CountDownLatch done = new CountDownLatch(1);
559 >        try {
560 >            for (int i = 0; i < tasks.length; i++) {
561 >                Runnable r = new CheckedRunnable() {
562 >                    public void realRun() throws InterruptedException {
563 >                        threadStarted.countDown();
564 >                        done.await();
565 >                    }};
566 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
567 >            }
568 >            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
569 >            BlockingQueue<Runnable> q = p.getQueue();
570 >            assertFalse(p.remove((Runnable)tasks[0]));
571 >            assertTrue(q.contains((Runnable)tasks[4]));
572 >            assertTrue(q.contains((Runnable)tasks[3]));
573 >            assertTrue(p.remove((Runnable)tasks[4]));
574 >            assertFalse(p.remove((Runnable)tasks[4]));
575 >            assertFalse(q.contains((Runnable)tasks[4]));
576 >            assertTrue(q.contains((Runnable)tasks[3]));
577 >            assertTrue(p.remove((Runnable)tasks[3]));
578 >            assertFalse(q.contains((Runnable)tasks[3]));
579 >        } finally {
580 >            done.countDown();
581 >            joinPool(p);
582 >        }
583 >    }
584 >
585 >    /**
586 >     * purge eventually removes cancelled tasks from the queue
587 >     */
588 >    public void testPurge() throws InterruptedException {
589 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
590 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
591 >        for (int i = 0; i < tasks.length; i++)
592 >            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
593 >                                  LONG_DELAY_MS, MILLISECONDS);
594 >        try {
595 >            int max = tasks.length;
596              if (tasks[4].cancel(true)) --max;
597              if (tasks[3].cancel(true)) --max;
598 <            one.purge();
599 <            long count = one.getTaskCount();
600 <            assertTrue(count > 0 && count <= max);
598 >            // There must eventually be an interference-free point at
599 >            // which purge will not fail. (At worst, when queue is empty.)
600 >            long startTime = System.nanoTime();
601 >            do {
602 >                p.purge();
603 >                long count = p.getTaskCount();
604 >                if (count == max)
605 >                    return;
606 >            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
607 >            fail("Purge failed to remove cancelled tasks");
608 >        } finally {
609 >            for (ScheduledFuture task : tasks)
610 >                task.cancel(true);
611 >            joinPool(p);
612 >        }
613 >    }
614 >
615 >    /**
616 >     * shutdownNow returns a list containing tasks that were not run
617 >     */
618 >    public void testShutdownNow() {
619 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
620 >        for (int i = 0; i < 5; i++)
621 >            p.schedule(new SmallPossiblyInterruptedRunnable(),
622 >                       LONG_DELAY_MS, MILLISECONDS);
623 >        try {
624 >            List<Runnable> l = p.shutdownNow();
625 >            assertTrue(p.isShutdown());
626 >            assertEquals(5, l.size());
627 >        } catch (SecurityException ok) {
628 >            // Allowed in case test doesn't have privs
629          } finally {
630 <            one.shutdown();
630 >            joinPool(p);
631          }
632      }
633  
634      /**
635 <     *  Test to verify shutDownNow returns a list
636 <     *  containing the correct number of elements
635 >     * In default setting, shutdown cancels periodic but not delayed
636 >     * tasks at shutdown
637       */
638 <    public void testShutDownNow(){
639 <        ScheduledExecutor one = new ScheduledExecutor(1);
640 <        for(int i = 0; i < 5; i++)
641 <            one.schedule(newRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
642 <        List l = one.shutdownNow();
643 <        assertTrue(one.isShutdown());
644 <        assertTrue(l.size() > 0 && l.size() <= 5);
638 >    public void testShutdown1() throws InterruptedException {
639 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
640 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
641 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
642 >
643 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
644 >        for (int i = 0; i < tasks.length; i++)
645 >            tasks[i] = p.schedule(new NoOpRunnable(),
646 >                                  SHORT_DELAY_MS, MILLISECONDS);
647 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
648 >        BlockingQueue<Runnable> q = p.getQueue();
649 >        for (ScheduledFuture task : tasks) {
650 >            assertFalse(task.isDone());
651 >            assertFalse(task.isCancelled());
652 >            assertTrue(q.contains(task));
653 >        }
654 >        assertTrue(p.isShutdown());
655 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
656 >        assertTrue(p.isTerminated());
657 >        for (ScheduledFuture task : tasks) {
658 >            assertTrue(task.isDone());
659 >            assertFalse(task.isCancelled());
660 >        }
661      }
662  
663 <    public void testShutDown1(){
663 >    /**
664 >     * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
665 >     * delayed tasks are cancelled at shutdown
666 >     */
667 >    public void testShutdown2() throws InterruptedException {
668 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
669 >        p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
670 >        assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
671 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
672 >        ScheduledFuture[] tasks = new ScheduledFuture[5];
673 >        for (int i = 0; i < tasks.length; i++)
674 >            tasks[i] = p.schedule(new NoOpRunnable(),
675 >                                  SHORT_DELAY_MS, MILLISECONDS);
676 >        BlockingQueue q = p.getQueue();
677 >        assertEquals(tasks.length, q.size());
678 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
679 >        assertTrue(p.isShutdown());
680 >        assertTrue(q.isEmpty());
681 >        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
682 >        assertTrue(p.isTerminated());
683 >        for (ScheduledFuture task : tasks) {
684 >            assertTrue(task.isDone());
685 >            assertTrue(task.isCancelled());
686 >        }
687 >    }
688 >
689 >    /**
690 >     * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
691 >     * periodic tasks are cancelled at shutdown
692 >     */
693 >    public void testShutdown3() throws InterruptedException {
694 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
695 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
696 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
697 >        p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
698 >        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
699 >        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
700 >        long initialDelay = LONG_DELAY_MS;
701 >        ScheduledFuture task =
702 >            p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
703 >                                  5, MILLISECONDS);
704 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
705 >        assertTrue(p.isShutdown());
706 >        assertTrue(p.getQueue().isEmpty());
707 >        assertTrue(task.isDone());
708 >        assertTrue(task.isCancelled());
709 >        joinPool(p);
710 >    }
711 >
712 >    /**
713 >     * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
714 >     * periodic tasks are not cancelled at shutdown
715 >     */
716 >    public void testShutdown4() throws InterruptedException {
717 >        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
718 >        final CountDownLatch counter = new CountDownLatch(2);
719          try {
720 <            ScheduledExecutor one = new ScheduledExecutor(1);
721 <            assertTrue(one.getExecuteExistingDelayedTasksAfterShutdownPolicy());
722 <            assertFalse(one.getContinueExistingPeriodicTasksAfterShutdownPolicy());
720 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
721 >            assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
722 >            assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
723 >            final Runnable r = new CheckedRunnable() {
724 >                public void realRun() {
725 >                    counter.countDown();
726 >                }};
727 >            ScheduledFuture task =
728 >                p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS);
729 >            assertFalse(task.isDone());
730 >            assertFalse(task.isCancelled());
731 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
732 >            assertFalse(task.isCancelled());
733 >            assertFalse(p.isTerminated());
734 >            assertTrue(p.isShutdown());
735 >            assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS));
736 >            assertFalse(task.isCancelled());
737 >            assertTrue(task.cancel(false));
738 >            assertTrue(task.isDone());
739 >            assertTrue(task.isCancelled());
740 >            assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
741 >            assertTrue(p.isTerminated());
742 >        }
743 >        finally {
744 >            joinPool(p);
745 >        }
746 >    }
747  
748 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
749 <            for(int i = 0; i < 5; i++)
750 <                tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS);
751 <            one.shutdown();
752 <            BlockingQueue q = one.getQueue();
753 <            for (Iterator it = q.iterator(); it.hasNext();) {
754 <                ScheduledCancellable t = (ScheduledCancellable)it.next();
755 <                assertFalse(t.isCancelled());
756 <            }
757 <            assertTrue(one.isShutdown());
758 <            Thread.sleep(SHORT_DELAY_MS);
759 <            for (int i = 0; i < 5; ++i) {
760 <                assertTrue(tasks[i].isDone());
761 <                assertFalse(tasks[i].isCancelled());
762 <            }
763 <            
748 >    /**
749 >     * completed submit of callable returns result
750 >     */
751 >    public void testSubmitCallable() throws Exception {
752 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
753 >        try {
754 >            Future<String> future = e.submit(new StringTask());
755 >            String result = future.get();
756 >            assertSame(TEST_STRING, result);
757 >        } finally {
758 >            joinPool(e);
759 >        }
760 >    }
761 >
762 >    /**
763 >     * completed submit of runnable returns successfully
764 >     */
765 >    public void testSubmitRunnable() throws Exception {
766 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
767 >        try {
768 >            Future<?> future = e.submit(new NoOpRunnable());
769 >            future.get();
770 >            assertTrue(future.isDone());
771 >        } finally {
772 >            joinPool(e);
773 >        }
774 >    }
775 >
776 >    /**
777 >     * completed submit of (runnable, result) returns result
778 >     */
779 >    public void testSubmitRunnable2() throws Exception {
780 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
781 >        try {
782 >            Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
783 >            String result = future.get();
784 >            assertSame(TEST_STRING, result);
785 >        } finally {
786 >            joinPool(e);
787 >        }
788 >    }
789 >
790 >    /**
791 >     * invokeAny(null) throws NPE
792 >     */
793 >    public void testInvokeAny1() throws Exception {
794 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
795 >        try {
796 >            e.invokeAny(null);
797 >            shouldThrow();
798 >        } catch (NullPointerException success) {
799 >        } finally {
800 >            joinPool(e);
801          }
802 <        catch(Exception ex) {
803 <            fail("unexpected exception");
802 >    }
803 >
804 >    /**
805 >     * invokeAny(empty collection) throws IAE
806 >     */
807 >    public void testInvokeAny2() throws Exception {
808 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
809 >        try {
810 >            e.invokeAny(new ArrayList<Callable<String>>());
811 >            shouldThrow();
812 >        } catch (IllegalArgumentException success) {
813 >        } finally {
814 >            joinPool(e);
815          }
816      }
817  
818 +    /**
819 +     * invokeAny(c) throws NPE if c has null elements
820 +     */
821 +    public void testInvokeAny3() throws Exception {
822 +        CountDownLatch latch = new CountDownLatch(1);
823 +        ExecutorService e = new ScheduledThreadPoolExecutor(2);
824 +        List<Callable<String>> l = new ArrayList<Callable<String>>();
825 +        l.add(latchAwaitingStringTask(latch));
826 +        l.add(null);
827 +        try {
828 +            e.invokeAny(l);
829 +            shouldThrow();
830 +        } catch (NullPointerException success) {
831 +        } finally {
832 +            latch.countDown();
833 +            joinPool(e);
834 +        }
835 +    }
836  
837 <    public void testShutDown2(){
837 >    /**
838 >     * invokeAny(c) throws ExecutionException if no task completes
839 >     */
840 >    public void testInvokeAny4() throws Exception {
841 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
842 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
843 >        l.add(new NPETask());
844          try {
845 <            ScheduledExecutor one = new ScheduledExecutor(1);
846 <            one.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
847 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
848 <            for(int i = 0; i < 5; i++)
849 <                tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS);
850 <            one.shutdown();
502 <            assertTrue(one.isShutdown());
503 <            BlockingQueue q = one.getQueue();
504 <            assertTrue(q.isEmpty());
505 <            Thread.sleep(SHORT_DELAY_MS);
506 <            assertTrue(one.isTerminated());
845 >            e.invokeAny(l);
846 >            shouldThrow();
847 >        } catch (ExecutionException success) {
848 >            assertTrue(success.getCause() instanceof NullPointerException);
849 >        } finally {
850 >            joinPool(e);
851          }
852 <        catch(Exception ex) {
853 <            fail("unexpected exception");
852 >    }
853 >
854 >    /**
855 >     * invokeAny(c) returns result of some task
856 >     */
857 >    public void testInvokeAny5() throws Exception {
858 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
859 >        try {
860 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
861 >            l.add(new StringTask());
862 >            l.add(new StringTask());
863 >            String result = e.invokeAny(l);
864 >            assertSame(TEST_STRING, result);
865 >        } finally {
866 >            joinPool(e);
867          }
868      }
869  
870 +    /**
871 +     * invokeAll(null) throws NPE
872 +     */
873 +    public void testInvokeAll1() throws Exception {
874 +        ExecutorService e = new ScheduledThreadPoolExecutor(2);
875 +        try {
876 +            e.invokeAll(null);
877 +            shouldThrow();
878 +        } catch (NullPointerException success) {
879 +        } finally {
880 +            joinPool(e);
881 +        }
882 +    }
883  
884 <    public void testShutDown3(){
884 >    /**
885 >     * invokeAll(empty collection) returns empty collection
886 >     */
887 >    public void testInvokeAll2() throws Exception {
888 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
889          try {
890 <            ScheduledExecutor one = new ScheduledExecutor(1);
891 <            one.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
892 <            ScheduledCancellable task =
893 <                one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS);
520 <            one.shutdown();
521 <            assertTrue(one.isShutdown());
522 <            BlockingQueue q = one.getQueue();
523 <            assertTrue(q.isEmpty());
524 <            Thread.sleep(SHORT_DELAY_MS);
525 <            assertTrue(one.isTerminated());
890 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
891 >            assertTrue(r.isEmpty());
892 >        } finally {
893 >            joinPool(e);
894          }
895 <        catch(Exception ex) {
896 <            fail("unexpected exception");
895 >    }
896 >
897 >    /**
898 >     * invokeAll(c) throws NPE if c has null elements
899 >     */
900 >    public void testInvokeAll3() throws Exception {
901 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
902 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
903 >        l.add(new StringTask());
904 >        l.add(null);
905 >        try {
906 >            e.invokeAll(l);
907 >            shouldThrow();
908 >        } catch (NullPointerException success) {
909 >        } finally {
910 >            joinPool(e);
911          }
912      }
913  
914 <    public void testShutDown4(){
915 <        ScheduledExecutor one = new ScheduledExecutor(1);
914 >    /**
915 >     * get of invokeAll(c) throws exception on failed task
916 >     */
917 >    public void testInvokeAll4() throws Exception {
918 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
919 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
920 >        l.add(new NPETask());
921 >        List<Future<String>> futures = e.invokeAll(l);
922 >        assertEquals(1, futures.size());
923          try {
924 <            one.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
925 <            ScheduledCancellable task =
926 <                one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS);
927 <            assertFalse(task.isCancelled());
928 <            one.shutdown();
929 <            assertFalse(task.isCancelled());
930 <            assertFalse(one.isTerminated());
931 <            assertTrue(one.isShutdown());
932 <            Thread.sleep(SHORT_DELAY_MS);
933 <            assertFalse(task.isCancelled());
934 <            task.cancel(true);
935 <            assertTrue(task.isCancelled());
936 <            Thread.sleep(SHORT_DELAY_MS);
937 <            assertTrue(one.isTerminated());
924 >            futures.get(0).get();
925 >            shouldThrow();
926 >        } catch (ExecutionException success) {
927 >            assertTrue(success.getCause() instanceof NullPointerException);
928 >        } finally {
929 >            joinPool(e);
930 >        }
931 >    }
932 >
933 >    /**
934 >     * invokeAll(c) returns results of all completed tasks
935 >     */
936 >    public void testInvokeAll5() throws Exception {
937 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 >        try {
939 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
940 >            l.add(new StringTask());
941 >            l.add(new StringTask());
942 >            List<Future<String>> futures = e.invokeAll(l);
943 >            assertEquals(2, futures.size());
944 >            for (Future<String> future : futures)
945 >                assertSame(TEST_STRING, future.get());
946 >        } finally {
947 >            joinPool(e);
948          }
949 <        catch(Exception ex) {
950 <            fail("unexpected exception");
949 >    }
950 >
951 >    /**
952 >     * timed invokeAny(null) throws NPE
953 >     */
954 >    public void testTimedInvokeAny1() throws Exception {
955 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
956 >        try {
957 >            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
958 >            shouldThrow();
959 >        } catch (NullPointerException success) {
960 >        } finally {
961 >            joinPool(e);
962          }
963 <        finally {
964 <            one.shutdownNow();
963 >    }
964 >
965 >    /**
966 >     * timed invokeAny(,,null) throws NPE
967 >     */
968 >    public void testTimedInvokeAnyNullTimeUnit() throws Exception {
969 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
970 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
971 >        l.add(new StringTask());
972 >        try {
973 >            e.invokeAny(l, MEDIUM_DELAY_MS, null);
974 >            shouldThrow();
975 >        } catch (NullPointerException success) {
976 >        } finally {
977 >            joinPool(e);
978 >        }
979 >    }
980 >
981 >    /**
982 >     * timed invokeAny(empty collection) throws IAE
983 >     */
984 >    public void testTimedInvokeAny2() throws Exception {
985 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
986 >        try {
987 >            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
988 >            shouldThrow();
989 >        } catch (IllegalArgumentException success) {
990 >        } finally {
991 >            joinPool(e);
992 >        }
993 >    }
994 >
995 >    /**
996 >     * timed invokeAny(c) throws NPE if c has null elements
997 >     */
998 >    public void testTimedInvokeAny3() throws Exception {
999 >        CountDownLatch latch = new CountDownLatch(1);
1000 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1001 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
1002 >        l.add(latchAwaitingStringTask(latch));
1003 >        l.add(null);
1004 >        try {
1005 >            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1006 >            shouldThrow();
1007 >        } catch (NullPointerException success) {
1008 >        } finally {
1009 >            latch.countDown();
1010 >            joinPool(e);
1011 >        }
1012 >    }
1013 >
1014 >    /**
1015 >     * timed invokeAny(c) throws ExecutionException if no task completes
1016 >     */
1017 >    public void testTimedInvokeAny4() throws Exception {
1018 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1019 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
1020 >        l.add(new NPETask());
1021 >        try {
1022 >            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1023 >            shouldThrow();
1024 >        } catch (ExecutionException success) {
1025 >            assertTrue(success.getCause() instanceof NullPointerException);
1026 >        } finally {
1027 >            joinPool(e);
1028 >        }
1029 >    }
1030 >
1031 >    /**
1032 >     * timed invokeAny(c) returns result of some task
1033 >     */
1034 >    public void testTimedInvokeAny5() throws Exception {
1035 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1036 >        try {
1037 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1038 >            l.add(new StringTask());
1039 >            l.add(new StringTask());
1040 >            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1041 >            assertSame(TEST_STRING, result);
1042 >        } finally {
1043 >            joinPool(e);
1044 >        }
1045 >    }
1046 >
1047 >    /**
1048 >     * timed invokeAll(null) throws NPE
1049 >     */
1050 >    public void testTimedInvokeAll1() throws Exception {
1051 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1052 >        try {
1053 >            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1054 >            shouldThrow();
1055 >        } catch (NullPointerException success) {
1056 >        } finally {
1057 >            joinPool(e);
1058 >        }
1059 >    }
1060 >
1061 >    /**
1062 >     * timed invokeAll(,,null) throws NPE
1063 >     */
1064 >    public void testTimedInvokeAllNullTimeUnit() throws Exception {
1065 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1066 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
1067 >        l.add(new StringTask());
1068 >        try {
1069 >            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1070 >            shouldThrow();
1071 >        } catch (NullPointerException success) {
1072 >        } finally {
1073 >            joinPool(e);
1074 >        }
1075 >    }
1076 >
1077 >    /**
1078 >     * timed invokeAll(empty collection) returns empty collection
1079 >     */
1080 >    public void testTimedInvokeAll2() throws Exception {
1081 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1082 >        try {
1083 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1084 >            assertTrue(r.isEmpty());
1085 >        } finally {
1086 >            joinPool(e);
1087 >        }
1088 >    }
1089 >
1090 >    /**
1091 >     * timed invokeAll(c) throws NPE if c has null elements
1092 >     */
1093 >    public void testTimedInvokeAll3() throws Exception {
1094 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1095 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
1096 >        l.add(new StringTask());
1097 >        l.add(null);
1098 >        try {
1099 >            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1100 >            shouldThrow();
1101 >        } catch (NullPointerException success) {
1102 >        } finally {
1103 >            joinPool(e);
1104 >        }
1105 >    }
1106 >
1107 >    /**
1108 >     * get of element of invokeAll(c) throws exception on failed task
1109 >     */
1110 >    public void testTimedInvokeAll4() throws Exception {
1111 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1112 >        List<Callable<String>> l = new ArrayList<Callable<String>>();
1113 >        l.add(new NPETask());
1114 >        List<Future<String>> futures =
1115 >            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1116 >        assertEquals(1, futures.size());
1117 >        try {
1118 >            futures.get(0).get();
1119 >            shouldThrow();
1120 >        } catch (ExecutionException success) {
1121 >            assertTrue(success.getCause() instanceof NullPointerException);
1122 >        } finally {
1123 >            joinPool(e);
1124 >        }
1125 >    }
1126 >
1127 >    /**
1128 >     * timed invokeAll(c) returns results of all completed tasks
1129 >     */
1130 >    public void testTimedInvokeAll5() throws Exception {
1131 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1132 >        try {
1133 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1134 >            l.add(new StringTask());
1135 >            l.add(new StringTask());
1136 >            List<Future<String>> futures =
1137 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1138 >            assertEquals(2, futures.size());
1139 >            for (Future<String> future : futures)
1140 >                assertSame(TEST_STRING, future.get());
1141 >        } finally {
1142 >            joinPool(e);
1143 >        }
1144 >    }
1145 >
1146 >    /**
1147 >     * timed invokeAll(c) cancels tasks not completed by timeout
1148 >     */
1149 >    public void testTimedInvokeAll6() throws Exception {
1150 >        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1151 >        try {
1152 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1153 >            l.add(new StringTask());
1154 >            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1155 >            l.add(new StringTask());
1156 >            List<Future<String>> futures =
1157 >                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1158 >            assertEquals(3, futures.size());
1159 >            Iterator<Future<String>> it = futures.iterator();
1160 >            Future<String> f1 = it.next();
1161 >            Future<String> f2 = it.next();
1162 >            Future<String> f3 = it.next();
1163 >            assertTrue(f1.isDone());
1164 >            assertTrue(f2.isDone());
1165 >            assertTrue(f3.isDone());
1166 >            assertFalse(f1.isCancelled());
1167 >            assertTrue(f2.isCancelled());
1168 >        } finally {
1169 >            joinPool(e);
1170          }
1171      }
1172  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines