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.21 by dl, Thu Jan 22 15:17:35 2004 UTC vs.
Revision 1.88 by jsr166, Sun Mar 26 02:00:39 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines