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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines