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.22 by jsr166, Mon Nov 2 20:28:32 2009 UTC vs.
Revision 1.66 by jsr166, Mon Oct 5 21:54:33 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines