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.58 by jsr166, Mon Sep 28 08:23:49 2015 UTC vs.
Revision 1.83 by jsr166, Wed Jan 4 06:09:58 2017 UTC

# Line 7 | Line 7
7   */
8  
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;
# Line 17 | Line 18 | import java.util.concurrent.Callable;
18   import java.util.concurrent.CancellationException;
19   import java.util.concurrent.CountDownLatch;
20   import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Executors;
21   import java.util.concurrent.ExecutorService;
22   import java.util.concurrent.Future;
23   import java.util.concurrent.RejectedExecutionException;
# Line 25 | Line 25 | import java.util.concurrent.ScheduledFut
25   import java.util.concurrent.ScheduledThreadPoolExecutor;
26   import java.util.concurrent.ThreadFactory;
27   import java.util.concurrent.ThreadPoolExecutor;
28 + import java.util.concurrent.atomic.AtomicBoolean;
29   import java.util.concurrent.atomic.AtomicInteger;
30 + import java.util.concurrent.atomic.AtomicLong;
31  
32   import junit.framework.Test;
33   import junit.framework.TestSuite;
# Line 42 | Line 44 | public class ScheduledExecutorTest exten
44       * execute successfully executes a runnable
45       */
46      public void testExecute() throws InterruptedException {
47 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
48 <        final CountDownLatch done = new CountDownLatch(1);
49 <        final Runnable task = new CheckedRunnable() {
50 <            public void realRun() {
51 <                done.countDown();
50 <            }};
51 <        try {
47 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
48 >        try (PoolCleaner cleaner = cleaner(p)) {
49 >            final CountDownLatch done = new CountDownLatch(1);
50 >            final Runnable task = new CheckedRunnable() {
51 >                public void realRun() { done.countDown(); }};
52              p.execute(task);
53 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
54 <        } finally {
55 <            joinPool(p);
53 >            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
54          }
55      }
56  
# Line 60 | Line 58 | public class ScheduledExecutorTest exten
58       * delayed schedule of callable successfully executes after delay
59       */
60      public void testSchedule1() throws Exception {
61 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
62 <        final long startTime = System.nanoTime();
63 <        final CountDownLatch done = new CountDownLatch(1);
64 <        try {
61 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
62 >        try (PoolCleaner cleaner = cleaner(p)) {
63 >            final long startTime = System.nanoTime();
64 >            final CountDownLatch done = new CountDownLatch(1);
65              Callable task = new CheckedCallable<Boolean>() {
66                  public Boolean realCall() {
67                      done.countDown();
# Line 74 | Line 72 | public class ScheduledExecutorTest exten
72              assertSame(Boolean.TRUE, f.get());
73              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
74              assertTrue(done.await(0L, MILLISECONDS));
77        } finally {
78            joinPool(p);
75          }
76      }
77  
# Line 83 | Line 79 | public class ScheduledExecutorTest exten
79       * delayed schedule of runnable successfully executes after delay
80       */
81      public void testSchedule3() throws Exception {
82 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
83 <        final long startTime = System.nanoTime();
84 <        final CountDownLatch done = new CountDownLatch(1);
85 <        try {
82 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
83 >        try (PoolCleaner cleaner = cleaner(p)) {
84 >            final long startTime = System.nanoTime();
85 >            final CountDownLatch done = new CountDownLatch(1);
86              Runnable task = new CheckedRunnable() {
87                  public void realRun() {
88                      done.countDown();
# Line 96 | Line 92 | public class ScheduledExecutorTest exten
92              await(done);
93              assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
94              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
99        } finally {
100            joinPool(p);
95          }
96      }
97  
# Line 105 | Line 99 | public class ScheduledExecutorTest exten
99       * scheduleAtFixedRate executes runnable after given initial delay
100       */
101      public void testSchedule4() throws Exception {
102 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
103 <        final long startTime = System.nanoTime();
104 <        final CountDownLatch done = new CountDownLatch(1);
105 <        try {
102 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
103 >        try (PoolCleaner cleaner = cleaner(p)) {
104 >            final long startTime = System.nanoTime();
105 >            final CountDownLatch done = new CountDownLatch(1);
106              Runnable task = new CheckedRunnable() {
107                  public void realRun() {
108                      done.countDown();
# Line 120 | Line 114 | public class ScheduledExecutorTest exten
114              await(done);
115              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
116              f.cancel(true);
123        } finally {
124            joinPool(p);
117          }
118      }
119  
# Line 129 | Line 121 | public class ScheduledExecutorTest exten
121       * scheduleWithFixedDelay executes runnable after given initial delay
122       */
123      public void testSchedule5() throws Exception {
124 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
125 <        final long startTime = System.nanoTime();
126 <        final CountDownLatch done = new CountDownLatch(1);
127 <        try {
124 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
125 >        try (PoolCleaner cleaner = cleaner(p)) {
126 >            final long startTime = System.nanoTime();
127 >            final CountDownLatch done = new CountDownLatch(1);
128              Runnable task = new CheckedRunnable() {
129                  public void realRun() {
130                      done.countDown();
# Line 144 | Line 136 | public class ScheduledExecutorTest exten
136              await(done);
137              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
138              f.cancel(true);
147        } finally {
148            joinPool(p);
139          }
140      }
141  
# Line 155 | Line 145 | public class ScheduledExecutorTest exten
145      }
146  
147      /**
148 <     * scheduleAtFixedRate executes series of tasks at given rate
148 >     * scheduleAtFixedRate executes series of tasks at given rate.
149 >     * Eventually, it must hold that:
150 >     *   cycles - 1 <= elapsedMillis/delay < cycles
151       */
152      public void testFixedRateSequence() throws InterruptedException {
153 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
154 <        try {
153 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
154 >        try (PoolCleaner cleaner = cleaner(p)) {
155              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
156 <                long startTime = System.nanoTime();
157 <                int cycles = 10;
156 >                final long startTime = System.nanoTime();
157 >                final int cycles = 8;
158                  final CountDownLatch done = new CountDownLatch(cycles);
159 <                Runnable task = new CheckedRunnable() {
159 >                final Runnable task = new CheckedRunnable() {
160                      public void realRun() { done.countDown(); }};
161 <                ScheduledFuture h =
161 >                final ScheduledFuture periodicTask =
162                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
163 <                done.await();
164 <                h.cancel(true);
165 <                double normalizedTime =
166 <                    (double) millisElapsedSince(startTime) / delay;
167 <                if (normalizedTime >= cycles - 1 &&
168 <                    normalizedTime <= cycles)
163 >                final int totalDelayMillis = (cycles - 1) * delay;
164 >                await(done, totalDelayMillis + LONG_DELAY_MS);
165 >                periodicTask.cancel(true);
166 >                final long elapsedMillis = millisElapsedSince(startTime);
167 >                assertTrue(elapsedMillis >= totalDelayMillis);
168 >                if (elapsedMillis <= cycles * delay)
169                      return;
170 +                // else retry with longer delay
171              }
172 <            throw new AssertionError("unexpected execution rate");
180 <        } finally {
181 <            joinPool(p);
172 >            fail("unexpected execution rate");
173          }
174      }
175  
176      /**
177 <     * scheduleWithFixedDelay executes series of tasks with given period
177 >     * scheduleWithFixedDelay executes series of tasks with given period.
178 >     * Eventually, it must hold that each task starts at least delay and at
179 >     * most 2 * delay after the termination of the previous task.
180       */
181      public void testFixedDelaySequence() throws InterruptedException {
182 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
183 <        try {
182 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
183 >        try (PoolCleaner cleaner = cleaner(p)) {
184              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
185 <                long startTime = System.nanoTime();
186 <                int cycles = 10;
185 >                final long startTime = System.nanoTime();
186 >                final AtomicLong previous = new AtomicLong(startTime);
187 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
188 >                final int cycles = 8;
189                  final CountDownLatch done = new CountDownLatch(cycles);
190 <                Runnable task = new CheckedRunnable() {
191 <                    public void realRun() { done.countDown(); }};
192 <                ScheduledFuture h =
190 >                final int d = delay;
191 >                final Runnable task = new CheckedRunnable() {
192 >                    public void realRun() {
193 >                        long now = System.nanoTime();
194 >                        long elapsedMillis
195 >                            = NANOSECONDS.toMillis(now - previous.get());
196 >                        if (done.getCount() == cycles) { // first execution
197 >                            if (elapsedMillis >= d)
198 >                                tryLongerDelay.set(true);
199 >                        } else {
200 >                            assertTrue(elapsedMillis >= d);
201 >                            if (elapsedMillis >= 2 * d)
202 >                                tryLongerDelay.set(true);
203 >                        }
204 >                        previous.set(now);
205 >                        done.countDown();
206 >                    }};
207 >                final ScheduledFuture periodicTask =
208                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
209 <                done.await();
210 <                h.cancel(true);
211 <                double normalizedTime =
212 <                    (double) millisElapsedSince(startTime) / delay;
213 <                if (normalizedTime >= cycles - 1 &&
214 <                    normalizedTime <= cycles)
209 >                final int totalDelayMillis = (cycles - 1) * delay;
210 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
211 >                periodicTask.cancel(true);
212 >                final long elapsedMillis = millisElapsedSince(startTime);
213 >                assertTrue(elapsedMillis >= totalDelayMillis);
214 >                if (!tryLongerDelay.get())
215                      return;
216 +                // else retry with longer delay
217              }
218 <            throw new AssertionError("unexpected execution rate");
208 <        } finally {
209 <            joinPool(p);
218 >            fail("unexpected execution rate");
219          }
220      }
221  
# Line 214 | Line 223 | public class ScheduledExecutorTest exten
223       * execute(null) throws NPE
224       */
225      public void testExecuteNull() throws InterruptedException {
226 <        ScheduledThreadPoolExecutor se = null;
227 <        try {
228 <            se = new ScheduledThreadPoolExecutor(1);
229 <            se.execute(null);
230 <            shouldThrow();
231 <        } catch (NullPointerException success) {}
232 <
224 <        joinPool(se);
226 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
227 >        try (PoolCleaner cleaner = cleaner(p)) {
228 >            try {
229 >                p.execute(null);
230 >                shouldThrow();
231 >            } catch (NullPointerException success) {}
232 >        }
233      }
234  
235      /**
236       * schedule(null) throws NPE
237       */
238      public void testScheduleNull() throws InterruptedException {
239 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
240 <        try {
241 <            TrackedCallable callable = null;
242 <            Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
243 <            shouldThrow();
244 <        } catch (NullPointerException success) {}
245 <        joinPool(se);
239 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
240 >        try (PoolCleaner cleaner = cleaner(p)) {
241 >            try {
242 >                TrackedCallable callable = null;
243 >                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
244 >                shouldThrow();
245 >            } catch (NullPointerException success) {}
246 >        }
247      }
248  
249      /**
250       * execute throws RejectedExecutionException if shutdown
251       */
252      public void testSchedule1_RejectedExecutionException() throws InterruptedException {
253 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
254 <        try {
255 <            se.shutdown();
256 <            se.schedule(new NoOpRunnable(),
257 <                        MEDIUM_DELAY_MS, MILLISECONDS);
258 <            shouldThrow();
259 <        } catch (RejectedExecutionException success) {
260 <        } catch (SecurityException ok) {
253 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
254 >        try (PoolCleaner cleaner = cleaner(p)) {
255 >            try {
256 >                p.shutdown();
257 >                p.schedule(new NoOpRunnable(),
258 >                           MEDIUM_DELAY_MS, MILLISECONDS);
259 >                shouldThrow();
260 >            } catch (RejectedExecutionException success) {
261 >            } catch (SecurityException ok) {}
262          }
253
254        joinPool(se);
263      }
264  
265      /**
266       * schedule throws RejectedExecutionException if shutdown
267       */
268      public void testSchedule2_RejectedExecutionException() throws InterruptedException {
269 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
270 <        try {
271 <            se.shutdown();
272 <            se.schedule(new NoOpCallable(),
273 <                        MEDIUM_DELAY_MS, MILLISECONDS);
274 <            shouldThrow();
275 <        } catch (RejectedExecutionException success) {
276 <        } catch (SecurityException ok) {
269 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
270 >        try (PoolCleaner cleaner = cleaner(p)) {
271 >            try {
272 >                p.shutdown();
273 >                p.schedule(new NoOpCallable(),
274 >                           MEDIUM_DELAY_MS, MILLISECONDS);
275 >                shouldThrow();
276 >            } catch (RejectedExecutionException success) {
277 >            } catch (SecurityException ok) {}
278          }
270        joinPool(se);
279      }
280  
281      /**
282       * schedule callable throws RejectedExecutionException if shutdown
283       */
284      public void testSchedule3_RejectedExecutionException() throws InterruptedException {
285 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
286 <        try {
287 <            se.shutdown();
288 <            se.schedule(new NoOpCallable(),
289 <                        MEDIUM_DELAY_MS, MILLISECONDS);
290 <            shouldThrow();
291 <        } catch (RejectedExecutionException success) {
292 <        } catch (SecurityException ok) {
285 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
286 >        try (PoolCleaner cleaner = cleaner(p)) {
287 >            try {
288 >                p.shutdown();
289 >                p.schedule(new NoOpCallable(),
290 >                           MEDIUM_DELAY_MS, MILLISECONDS);
291 >                shouldThrow();
292 >            } catch (RejectedExecutionException success) {
293 >            } catch (SecurityException ok) {}
294          }
286        joinPool(se);
295      }
296  
297      /**
298       * scheduleAtFixedRate throws RejectedExecutionException if shutdown
299       */
300      public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
301 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
302 <        try {
303 <            se.shutdown();
304 <            se.scheduleAtFixedRate(new NoOpRunnable(),
305 <                                   MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
306 <            shouldThrow();
307 <        } catch (RejectedExecutionException success) {
308 <        } catch (SecurityException ok) {
301 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
302 >        try (PoolCleaner cleaner = cleaner(p)) {
303 >            try {
304 >                p.shutdown();
305 >                p.scheduleAtFixedRate(new NoOpRunnable(),
306 >                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
307 >                shouldThrow();
308 >            } catch (RejectedExecutionException success) {
309 >            } catch (SecurityException ok) {}
310          }
302        joinPool(se);
311      }
312  
313      /**
314       * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
315       */
316      public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
317 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
318 <        try {
319 <            se.shutdown();
320 <            se.scheduleWithFixedDelay(new NoOpRunnable(),
321 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
322 <            shouldThrow();
323 <        } catch (RejectedExecutionException success) {
324 <        } catch (SecurityException ok) {
317 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
318 >        try (PoolCleaner cleaner = cleaner(p)) {
319 >            try {
320 >                p.shutdown();
321 >                p.scheduleWithFixedDelay(new NoOpRunnable(),
322 >                                         MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
323 >                shouldThrow();
324 >            } catch (RejectedExecutionException success) {
325 >            } catch (SecurityException ok) {}
326          }
318        joinPool(se);
327      }
328  
329      /**
# Line 323 | Line 331 | public class ScheduledExecutorTest exten
331       * thread becomes active
332       */
333      public void testGetActiveCount() throws InterruptedException {
326        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
327        final CountDownLatch threadStarted = new CountDownLatch(1);
334          final CountDownLatch done = new CountDownLatch(1);
335 <        try {
335 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
336 >        try (PoolCleaner cleaner = cleaner(p, done)) {
337 >            final CountDownLatch threadStarted = new CountDownLatch(1);
338              assertEquals(0, p.getActiveCount());
339              p.execute(new CheckedRunnable() {
340                  public void realRun() throws InterruptedException {
341                      threadStarted.countDown();
342                      assertEquals(1, p.getActiveCount());
343 <                    done.await();
343 >                    await(done);
344                  }});
345 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
345 >            await(threadStarted);
346              assertEquals(1, p.getActiveCount());
339        } finally {
340            done.countDown();
341            joinPool(p);
347          }
348      }
349  
# Line 348 | Line 353 | public class ScheduledExecutorTest exten
353       */
354      public void testGetCompletedTaskCount() throws InterruptedException {
355          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
356 <        final CountDownLatch threadStarted = new CountDownLatch(1);
357 <        final CountDownLatch threadProceed = new CountDownLatch(1);
358 <        final CountDownLatch threadDone = new CountDownLatch(1);
359 <        try {
356 >        try (PoolCleaner cleaner = cleaner(p)) {
357 >            final CountDownLatch threadStarted = new CountDownLatch(1);
358 >            final CountDownLatch threadProceed = new CountDownLatch(1);
359 >            final CountDownLatch threadDone = new CountDownLatch(1);
360              assertEquals(0, p.getCompletedTaskCount());
361              p.execute(new CheckedRunnable() {
362                  public void realRun() throws InterruptedException {
# Line 370 | Line 375 | public class ScheduledExecutorTest exten
375                      fail("timed out");
376                  Thread.yield();
377              }
373        } finally {
374            joinPool(p);
378          }
379      }
380  
# Line 380 | Line 383 | public class ScheduledExecutorTest exten
383       */
384      public void testGetCorePoolSize() throws InterruptedException {
385          ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
386 <        assertEquals(1, p.getCorePoolSize());
387 <        joinPool(p);
386 >        try (PoolCleaner cleaner = cleaner(p)) {
387 >            assertEquals(1, p.getCorePoolSize());
388 >        }
389      }
390  
391      /**
# Line 393 | Line 397 | public class ScheduledExecutorTest exten
397          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
398          final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
399          final CountDownLatch done = new CountDownLatch(1);
400 <        try {
400 >        try (PoolCleaner cleaner = cleaner(p, done)) {
401              assertEquals(0, p.getLargestPoolSize());
402              for (int i = 0; i < THREADS; i++)
403                  p.execute(new CheckedRunnable() {
404                      public void realRun() throws InterruptedException {
405                          threadsStarted.countDown();
406 <                        done.await();
406 >                        await(done);
407                          assertEquals(THREADS, p.getLargestPoolSize());
408                      }});
409 <            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
406 <            assertEquals(THREADS, p.getLargestPoolSize());
407 <        } finally {
408 <            done.countDown();
409 <            joinPool(p);
409 >            await(threadsStarted);
410              assertEquals(THREADS, p.getLargestPoolSize());
411          }
412 +        assertEquals(THREADS, p.getLargestPoolSize());
413      }
414  
415      /**
# Line 419 | Line 420 | public class ScheduledExecutorTest exten
420          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
421          final CountDownLatch threadStarted = new CountDownLatch(1);
422          final CountDownLatch done = new CountDownLatch(1);
423 <        try {
423 >        try (PoolCleaner cleaner = cleaner(p, done)) {
424              assertEquals(0, p.getPoolSize());
425              p.execute(new CheckedRunnable() {
426                  public void realRun() throws InterruptedException {
427                      threadStarted.countDown();
428                      assertEquals(1, p.getPoolSize());
429 <                    done.await();
429 >                    await(done);
430                  }});
431 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
431 >            await(threadStarted);
432              assertEquals(1, p.getPoolSize());
432        } finally {
433            done.countDown();
434            joinPool(p);
433          }
434      }
435  
# Line 440 | Line 438 | public class ScheduledExecutorTest exten
438       * submitted
439       */
440      public void testGetTaskCount() throws InterruptedException {
441 <        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
444 <        final CountDownLatch threadStarted = new CountDownLatch(1);
441 >        final int TASKS = 3;
442          final CountDownLatch done = new CountDownLatch(1);
443 <        final int TASKS = 5;
444 <        try {
443 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
444 >        try (PoolCleaner cleaner = cleaner(p, done)) {
445 >            final CountDownLatch threadStarted = new CountDownLatch(1);
446              assertEquals(0, p.getTaskCount());
447 <            for (int i = 0; i < TASKS; i++)
447 >            assertEquals(0, p.getCompletedTaskCount());
448 >            p.execute(new CheckedRunnable() {
449 >                public void realRun() throws InterruptedException {
450 >                    threadStarted.countDown();
451 >                    await(done);
452 >                }});
453 >            await(threadStarted);
454 >            assertEquals(1, p.getTaskCount());
455 >            assertEquals(0, p.getCompletedTaskCount());
456 >            for (int i = 0; i < TASKS; i++) {
457 >                assertEquals(1 + i, p.getTaskCount());
458                  p.execute(new CheckedRunnable() {
459                      public void realRun() throws InterruptedException {
460                          threadStarted.countDown();
461 <                        done.await();
461 >                        assertEquals(1 + TASKS, p.getTaskCount());
462 >                        await(done);
463                      }});
464 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
465 <            assertEquals(TASKS, p.getTaskCount());
466 <        } finally {
458 <            done.countDown();
459 <            joinPool(p);
464 >            }
465 >            assertEquals(1 + TASKS, p.getTaskCount());
466 >            assertEquals(0, p.getCompletedTaskCount());
467          }
468 +        assertEquals(1 + TASKS, p.getTaskCount());
469 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
470      }
471  
472      /**
473       * getThreadFactory returns factory in constructor if not set
474       */
475      public void testGetThreadFactory() throws InterruptedException {
476 <        ThreadFactory tf = new SimpleThreadFactory();
477 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
478 <        assertSame(tf, p.getThreadFactory());
479 <        joinPool(p);
476 >        final ThreadFactory threadFactory = new SimpleThreadFactory();
477 >        final ScheduledThreadPoolExecutor p =
478 >            new ScheduledThreadPoolExecutor(1, threadFactory);
479 >        try (PoolCleaner cleaner = cleaner(p)) {
480 >            assertSame(threadFactory, p.getThreadFactory());
481 >        }
482      }
483  
484      /**
485       * setThreadFactory sets the thread factory returned by getThreadFactory
486       */
487      public void testSetThreadFactory() throws InterruptedException {
488 <        ThreadFactory tf = new SimpleThreadFactory();
489 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
490 <        p.setThreadFactory(tf);
491 <        assertSame(tf, p.getThreadFactory());
492 <        joinPool(p);
488 >        ThreadFactory threadFactory = new SimpleThreadFactory();
489 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
490 >        try (PoolCleaner cleaner = cleaner(p)) {
491 >            p.setThreadFactory(threadFactory);
492 >            assertSame(threadFactory, p.getThreadFactory());
493 >        }
494      }
495  
496      /**
497       * setThreadFactory(null) throws NPE
498       */
499      public void testSetThreadFactoryNull() throws InterruptedException {
500 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
501 <        try {
502 <            p.setThreadFactory(null);
503 <            shouldThrow();
504 <        } catch (NullPointerException success) {
505 <        } finally {
494 <            joinPool(p);
500 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
501 >        try (PoolCleaner cleaner = cleaner(p)) {
502 >            try {
503 >                p.setThreadFactory(null);
504 >                shouldThrow();
505 >            } catch (NullPointerException success) {}
506          }
507      }
508  
# Line 499 | Line 510 | public class ScheduledExecutorTest exten
510       * isShutdown is false before shutdown, true after
511       */
512      public void testIsShutdown() {
513 <
514 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
515 <        try {
516 <            assertFalse(p.isShutdown());
517 <        }
518 <        finally {
519 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
513 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
514 >        assertFalse(p.isShutdown());
515 >        try (PoolCleaner cleaner = cleaner(p)) {
516 >            try {
517 >                p.shutdown();
518 >                assertTrue(p.isShutdown());
519 >            } catch (SecurityException ok) {}
520          }
510        assertTrue(p.isShutdown());
521      }
522  
523      /**
# Line 515 | Line 525 | public class ScheduledExecutorTest exten
525       */
526      public void testIsTerminated() throws InterruptedException {
527          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
528 <        final CountDownLatch threadStarted = new CountDownLatch(1);
529 <        final CountDownLatch done = new CountDownLatch(1);
530 <        assertFalse(p.isTerminated());
531 <        try {
528 >        try (PoolCleaner cleaner = cleaner(p)) {
529 >            final CountDownLatch threadStarted = new CountDownLatch(1);
530 >            final CountDownLatch done = new CountDownLatch(1);
531 >            assertFalse(p.isTerminated());
532              p.execute(new CheckedRunnable() {
533                  public void realRun() throws InterruptedException {
534                      assertFalse(p.isTerminated());
535                      threadStarted.countDown();
536 <                    done.await();
536 >                    await(done);
537                  }});
538 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
538 >            await(threadStarted);
539              assertFalse(p.isTerminating());
540              done.countDown();
531        } finally {
541              try { p.shutdown(); } catch (SecurityException ok) { return; }
542 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
543 +            assertTrue(p.isTerminated());
544          }
534        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
535        assertTrue(p.isTerminated());
545      }
546  
547      /**
# Line 542 | Line 551 | public class ScheduledExecutorTest exten
551          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
552          final CountDownLatch threadStarted = new CountDownLatch(1);
553          final CountDownLatch done = new CountDownLatch(1);
554 <        try {
554 >        try (PoolCleaner cleaner = cleaner(p)) {
555              assertFalse(p.isTerminating());
556              p.execute(new CheckedRunnable() {
557                  public void realRun() throws InterruptedException {
558                      assertFalse(p.isTerminating());
559                      threadStarted.countDown();
560 <                    done.await();
560 >                    await(done);
561                  }});
562 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
562 >            await(threadStarted);
563              assertFalse(p.isTerminating());
564              done.countDown();
556        } finally {
565              try { p.shutdown(); } catch (SecurityException ok) { return; }
566 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
567 +            assertTrue(p.isTerminated());
568 +            assertFalse(p.isTerminating());
569          }
559        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
560        assertTrue(p.isTerminated());
561        assertFalse(p.isTerminating());
570      }
571  
572      /**
573       * getQueue returns the work queue, which contains queued tasks
574       */
575      public void testGetQueue() throws InterruptedException {
568        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
569        final CountDownLatch threadStarted = new CountDownLatch(1);
576          final CountDownLatch done = new CountDownLatch(1);
577 <        try {
577 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
578 >        try (PoolCleaner cleaner = cleaner(p, done)) {
579 >            final CountDownLatch threadStarted = new CountDownLatch(1);
580              ScheduledFuture[] tasks = new ScheduledFuture[5];
581              for (int i = 0; i < tasks.length; i++) {
582                  Runnable r = new CheckedRunnable() {
583                      public void realRun() throws InterruptedException {
584                          threadStarted.countDown();
585 <                        done.await();
585 >                        await(done);
586                      }};
587                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
588              }
589 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
589 >            await(threadStarted);
590              BlockingQueue<Runnable> q = p.getQueue();
591              assertTrue(q.contains(tasks[tasks.length - 1]));
592              assertFalse(q.contains(tasks[0]));
585        } finally {
586            done.countDown();
587            joinPool(p);
593          }
594      }
595  
# Line 592 | Line 597 | public class ScheduledExecutorTest exten
597       * remove(task) removes queued task, and fails to remove active task
598       */
599      public void testRemove() throws InterruptedException {
595        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
596        ScheduledFuture[] tasks = new ScheduledFuture[5];
597        final CountDownLatch threadStarted = new CountDownLatch(1);
600          final CountDownLatch done = new CountDownLatch(1);
601 <        try {
601 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
602 >        try (PoolCleaner cleaner = cleaner(p, done)) {
603 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
604 >            final CountDownLatch threadStarted = new CountDownLatch(1);
605              for (int i = 0; i < tasks.length; i++) {
606                  Runnable r = new CheckedRunnable() {
607                      public void realRun() throws InterruptedException {
608                          threadStarted.countDown();
609 <                        done.await();
609 >                        await(done);
610                      }};
611                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
612              }
613 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
613 >            await(threadStarted);
614              BlockingQueue<Runnable> q = p.getQueue();
615              assertFalse(p.remove((Runnable)tasks[0]));
616              assertTrue(q.contains((Runnable)tasks[4]));
# Line 616 | Line 621 | public class ScheduledExecutorTest exten
621              assertTrue(q.contains((Runnable)tasks[3]));
622              assertTrue(p.remove((Runnable)tasks[3]));
623              assertFalse(q.contains((Runnable)tasks[3]));
619        } finally {
620            done.countDown();
621            joinPool(p);
624          }
625      }
626  
# Line 626 | Line 628 | public class ScheduledExecutorTest exten
628       * purge eventually removes cancelled tasks from the queue
629       */
630      public void testPurge() throws InterruptedException {
631 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
632 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
633 <        for (int i = 0; i < tasks.length; i++)
634 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
635 <                                  LONG_DELAY_MS, MILLISECONDS);
636 <        try {
631 >        final ScheduledFuture[] tasks = new ScheduledFuture[5];
632 >        final Runnable releaser = new Runnable() { public void run() {
633 >            for (ScheduledFuture task : tasks)
634 >                if (task != null) task.cancel(true); }};
635 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
636 >        try (PoolCleaner cleaner = cleaner(p, releaser)) {
637 >            for (int i = 0; i < tasks.length; i++)
638 >                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
639 >                                      LONG_DELAY_MS, MILLISECONDS);
640              int max = tasks.length;
641              if (tasks[4].cancel(true)) --max;
642              if (tasks[3].cancel(true)) --max;
# Line 643 | Line 648 | public class ScheduledExecutorTest exten
648                  long count = p.getTaskCount();
649                  if (count == max)
650                      return;
651 <            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
651 >            } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
652              fail("Purge failed to remove cancelled tasks");
648        } finally {
649            for (ScheduledFuture task : tasks)
650                task.cancel(true);
651            joinPool(p);
653          }
654      }
655  
# Line 662 | Line 663 | public class ScheduledExecutorTest exten
663          final AtomicInteger ran = new AtomicInteger(0);
664          final ScheduledThreadPoolExecutor p =
665              new ScheduledThreadPoolExecutor(poolSize);
666 <        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
666 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
667          Runnable waiter = new CheckedRunnable() { public void realRun() {
668              threadsStarted.countDown();
669              try {
# Line 672 | Line 673 | public class ScheduledExecutorTest exten
673          }};
674          for (int i = 0; i < count; i++)
675              p.execute(waiter);
676 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
676 >        await(threadsStarted);
677          assertEquals(poolSize, p.getActiveCount());
678          assertEquals(0, p.getCompletedTaskCount());
679          final List<Runnable> queuedTasks;
# Line 695 | Line 696 | public class ScheduledExecutorTest exten
696       * and those tasks are drained from the queue
697       */
698      public void testShutdownNow_delayedTasks() throws InterruptedException {
699 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
699 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
700          List<ScheduledFuture> tasks = new ArrayList<>();
701          for (int i = 0; i < 3; i++) {
702              Runnable r = new NoOpRunnable();
# Line 822 | Line 823 | public class ScheduledExecutorTest exten
823       * completed submit of callable returns result
824       */
825      public void testSubmitCallable() throws Exception {
826 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
827 <        try {
826 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
827 >        try (PoolCleaner cleaner = cleaner(e)) {
828              Future<String> future = e.submit(new StringTask());
829              String result = future.get();
830              assertSame(TEST_STRING, result);
830        } finally {
831            joinPool(e);
831          }
832      }
833  
# Line 836 | Line 835 | public class ScheduledExecutorTest exten
835       * completed submit of runnable returns successfully
836       */
837      public void testSubmitRunnable() throws Exception {
838 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
839 <        try {
838 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
839 >        try (PoolCleaner cleaner = cleaner(e)) {
840              Future<?> future = e.submit(new NoOpRunnable());
841              future.get();
842              assertTrue(future.isDone());
844        } finally {
845            joinPool(e);
843          }
844      }
845  
# Line 850 | Line 847 | public class ScheduledExecutorTest exten
847       * completed submit of (runnable, result) returns result
848       */
849      public void testSubmitRunnable2() throws Exception {
850 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
851 <        try {
850 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
851 >        try (PoolCleaner cleaner = cleaner(e)) {
852              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
853              String result = future.get();
854              assertSame(TEST_STRING, result);
858        } finally {
859            joinPool(e);
855          }
856      }
857  
# Line 864 | Line 859 | public class ScheduledExecutorTest exten
859       * invokeAny(null) throws NPE
860       */
861      public void testInvokeAny1() throws Exception {
862 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
863 <        try {
864 <            e.invokeAny(null);
865 <            shouldThrow();
866 <        } catch (NullPointerException success) {
867 <        } finally {
873 <            joinPool(e);
862 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
863 >        try (PoolCleaner cleaner = cleaner(e)) {
864 >            try {
865 >                e.invokeAny(null);
866 >                shouldThrow();
867 >            } catch (NullPointerException success) {}
868          }
869      }
870  
# Line 878 | Line 872 | public class ScheduledExecutorTest exten
872       * invokeAny(empty collection) throws IAE
873       */
874      public void testInvokeAny2() throws Exception {
875 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
876 <        try {
877 <            e.invokeAny(new ArrayList<Callable<String>>());
878 <            shouldThrow();
879 <        } catch (IllegalArgumentException success) {
880 <        } finally {
887 <            joinPool(e);
875 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
876 >        try (PoolCleaner cleaner = cleaner(e)) {
877 >            try {
878 >                e.invokeAny(new ArrayList<Callable<String>>());
879 >                shouldThrow();
880 >            } catch (IllegalArgumentException success) {}
881          }
882      }
883  
# Line 893 | Line 886 | public class ScheduledExecutorTest exten
886       */
887      public void testInvokeAny3() throws Exception {
888          CountDownLatch latch = new CountDownLatch(1);
889 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
890 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
891 <        l.add(latchAwaitingStringTask(latch));
892 <        l.add(null);
893 <        try {
894 <            e.invokeAny(l);
895 <            shouldThrow();
896 <        } catch (NullPointerException success) {
897 <        } finally {
889 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
890 >        try (PoolCleaner cleaner = cleaner(e)) {
891 >            List<Callable<String>> l = new ArrayList<>();
892 >            l.add(latchAwaitingStringTask(latch));
893 >            l.add(null);
894 >            try {
895 >                e.invokeAny(l);
896 >                shouldThrow();
897 >            } catch (NullPointerException success) {}
898              latch.countDown();
906            joinPool(e);
899          }
900      }
901  
# Line 911 | Line 903 | public class ScheduledExecutorTest exten
903       * invokeAny(c) throws ExecutionException if no task completes
904       */
905      public void testInvokeAny4() throws Exception {
906 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
907 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
908 <        l.add(new NPETask());
909 <        try {
910 <            e.invokeAny(l);
911 <            shouldThrow();
912 <        } catch (ExecutionException success) {
913 <            assertTrue(success.getCause() instanceof NullPointerException);
914 <        } finally {
915 <            joinPool(e);
906 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
907 >        try (PoolCleaner cleaner = cleaner(e)) {
908 >            List<Callable<String>> l = new ArrayList<>();
909 >            l.add(new NPETask());
910 >            try {
911 >                e.invokeAny(l);
912 >                shouldThrow();
913 >            } catch (ExecutionException success) {
914 >                assertTrue(success.getCause() instanceof NullPointerException);
915 >            }
916          }
917      }
918  
# Line 928 | Line 920 | public class ScheduledExecutorTest exten
920       * invokeAny(c) returns result of some task
921       */
922      public void testInvokeAny5() throws Exception {
923 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
924 <        try {
925 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
923 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
924 >        try (PoolCleaner cleaner = cleaner(e)) {
925 >            List<Callable<String>> l = new ArrayList<>();
926              l.add(new StringTask());
927              l.add(new StringTask());
928              String result = e.invokeAny(l);
929              assertSame(TEST_STRING, result);
938        } finally {
939            joinPool(e);
930          }
931      }
932  
# Line 944 | Line 934 | public class ScheduledExecutorTest exten
934       * invokeAll(null) throws NPE
935       */
936      public void testInvokeAll1() throws Exception {
937 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 <        try {
939 <            e.invokeAll(null);
940 <            shouldThrow();
941 <        } catch (NullPointerException success) {
942 <        } finally {
953 <            joinPool(e);
937 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 >        try (PoolCleaner cleaner = cleaner(e)) {
939 >            try {
940 >                e.invokeAll(null);
941 >                shouldThrow();
942 >            } catch (NullPointerException success) {}
943          }
944      }
945  
# Line 958 | Line 947 | public class ScheduledExecutorTest exten
947       * invokeAll(empty collection) returns empty collection
948       */
949      public void testInvokeAll2() throws Exception {
950 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
951 <        try {
950 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
951 >        try (PoolCleaner cleaner = cleaner(e)) {
952              List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
953              assertTrue(r.isEmpty());
965        } finally {
966            joinPool(e);
954          }
955      }
956  
# Line 971 | Line 958 | public class ScheduledExecutorTest exten
958       * invokeAll(c) throws NPE if c has null elements
959       */
960      public void testInvokeAll3() throws Exception {
961 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
962 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
963 <        l.add(new StringTask());
964 <        l.add(null);
965 <        try {
966 <            e.invokeAll(l);
967 <            shouldThrow();
968 <        } catch (NullPointerException success) {
969 <        } finally {
983 <            joinPool(e);
961 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
962 >        try (PoolCleaner cleaner = cleaner(e)) {
963 >            List<Callable<String>> l = new ArrayList<>();
964 >            l.add(new StringTask());
965 >            l.add(null);
966 >            try {
967 >                e.invokeAll(l);
968 >                shouldThrow();
969 >            } catch (NullPointerException success) {}
970          }
971      }
972  
# Line 988 | Line 974 | public class ScheduledExecutorTest exten
974       * get of invokeAll(c) throws exception on failed task
975       */
976      public void testInvokeAll4() throws Exception {
977 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
978 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
979 <        l.add(new NPETask());
980 <        List<Future<String>> futures = e.invokeAll(l);
981 <        assertEquals(1, futures.size());
982 <        try {
983 <            futures.get(0).get();
984 <            shouldThrow();
985 <        } catch (ExecutionException success) {
986 <            assertTrue(success.getCause() instanceof NullPointerException);
987 <        } finally {
988 <            joinPool(e);
977 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
978 >        try (PoolCleaner cleaner = cleaner(e)) {
979 >            List<Callable<String>> l = new ArrayList<>();
980 >            l.add(new NPETask());
981 >            List<Future<String>> futures = e.invokeAll(l);
982 >            assertEquals(1, futures.size());
983 >            try {
984 >                futures.get(0).get();
985 >                shouldThrow();
986 >            } catch (ExecutionException success) {
987 >                assertTrue(success.getCause() instanceof NullPointerException);
988 >            }
989          }
990      }
991  
# Line 1007 | Line 993 | public class ScheduledExecutorTest exten
993       * invokeAll(c) returns results of all completed tasks
994       */
995      public void testInvokeAll5() throws Exception {
996 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
997 <        try {
998 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
996 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
997 >        try (PoolCleaner cleaner = cleaner(e)) {
998 >            List<Callable<String>> l = new ArrayList<>();
999              l.add(new StringTask());
1000              l.add(new StringTask());
1001              List<Future<String>> futures = e.invokeAll(l);
1002              assertEquals(2, futures.size());
1003              for (Future<String> future : futures)
1004                  assertSame(TEST_STRING, future.get());
1019        } finally {
1020            joinPool(e);
1005          }
1006      }
1007  
# Line 1025 | Line 1009 | public class ScheduledExecutorTest exten
1009       * timed invokeAny(null) throws NPE
1010       */
1011      public void testTimedInvokeAny1() throws Exception {
1012 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1013 <        try {
1014 <            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1015 <            shouldThrow();
1016 <        } catch (NullPointerException success) {
1017 <        } finally {
1034 <            joinPool(e);
1012 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1013 >        try (PoolCleaner cleaner = cleaner(e)) {
1014 >            try {
1015 >                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1016 >                shouldThrow();
1017 >            } catch (NullPointerException success) {}
1018          }
1019      }
1020  
# Line 1039 | Line 1022 | public class ScheduledExecutorTest exten
1022       * timed invokeAny(,,null) throws NPE
1023       */
1024      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1025 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1026 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1027 <        l.add(new StringTask());
1028 <        try {
1029 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
1030 <            shouldThrow();
1031 <        } catch (NullPointerException success) {
1032 <        } finally {
1050 <            joinPool(e);
1025 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1026 >        try (PoolCleaner cleaner = cleaner(e)) {
1027 >            List<Callable<String>> l = new ArrayList<>();
1028 >            l.add(new StringTask());
1029 >            try {
1030 >                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1031 >                shouldThrow();
1032 >            } catch (NullPointerException success) {}
1033          }
1034      }
1035  
# Line 1055 | Line 1037 | public class ScheduledExecutorTest exten
1037       * timed invokeAny(empty collection) throws IAE
1038       */
1039      public void testTimedInvokeAny2() throws Exception {
1040 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1041 <        try {
1042 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1043 <            shouldThrow();
1044 <        } catch (IllegalArgumentException success) {
1045 <        } finally {
1064 <            joinPool(e);
1040 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1041 >        try (PoolCleaner cleaner = cleaner(e)) {
1042 >            try {
1043 >                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1044 >                shouldThrow();
1045 >            } catch (IllegalArgumentException success) {}
1046          }
1047      }
1048  
# Line 1070 | Line 1051 | public class ScheduledExecutorTest exten
1051       */
1052      public void testTimedInvokeAny3() throws Exception {
1053          CountDownLatch latch = new CountDownLatch(1);
1054 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1055 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1056 <        l.add(latchAwaitingStringTask(latch));
1057 <        l.add(null);
1058 <        try {
1059 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1060 <            shouldThrow();
1061 <        } catch (NullPointerException success) {
1062 <        } finally {
1054 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1055 >        try (PoolCleaner cleaner = cleaner(e)) {
1056 >            List<Callable<String>> l = new ArrayList<>();
1057 >            l.add(latchAwaitingStringTask(latch));
1058 >            l.add(null);
1059 >            try {
1060 >                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1061 >                shouldThrow();
1062 >            } catch (NullPointerException success) {}
1063              latch.countDown();
1083            joinPool(e);
1064          }
1065      }
1066  
# Line 1088 | Line 1068 | public class ScheduledExecutorTest exten
1068       * timed invokeAny(c) throws ExecutionException if no task completes
1069       */
1070      public void testTimedInvokeAny4() throws Exception {
1071 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1072 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1073 <        l.add(new NPETask());
1074 <        try {
1075 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1076 <            shouldThrow();
1077 <        } catch (ExecutionException success) {
1078 <            assertTrue(success.getCause() instanceof NullPointerException);
1079 <        } finally {
1080 <            joinPool(e);
1071 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1072 >        try (PoolCleaner cleaner = cleaner(e)) {
1073 >            long startTime = System.nanoTime();
1074 >            List<Callable<String>> l = new ArrayList<>();
1075 >            l.add(new NPETask());
1076 >            try {
1077 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1078 >                shouldThrow();
1079 >            } catch (ExecutionException success) {
1080 >                assertTrue(success.getCause() instanceof NullPointerException);
1081 >            }
1082 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1083          }
1084      }
1085  
# Line 1105 | Line 1087 | public class ScheduledExecutorTest exten
1087       * timed invokeAny(c) returns result of some task
1088       */
1089      public void testTimedInvokeAny5() throws Exception {
1090 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1091 <        try {
1092 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1090 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1091 >        try (PoolCleaner cleaner = cleaner(e)) {
1092 >            long startTime = System.nanoTime();
1093 >            List<Callable<String>> l = new ArrayList<>();
1094              l.add(new StringTask());
1095              l.add(new StringTask());
1096 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1096 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1097              assertSame(TEST_STRING, result);
1098 <        } finally {
1116 <            joinPool(e);
1098 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1099          }
1100      }
1101  
# Line 1121 | Line 1103 | public class ScheduledExecutorTest exten
1103       * timed invokeAll(null) throws NPE
1104       */
1105      public void testTimedInvokeAll1() throws Exception {
1106 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1107 <        try {
1108 <            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1109 <            shouldThrow();
1110 <        } catch (NullPointerException success) {
1111 <        } finally {
1130 <            joinPool(e);
1106 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1107 >        try (PoolCleaner cleaner = cleaner(e)) {
1108 >            try {
1109 >                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1110 >                shouldThrow();
1111 >            } catch (NullPointerException success) {}
1112          }
1113      }
1114  
# Line 1135 | Line 1116 | public class ScheduledExecutorTest exten
1116       * timed invokeAll(,,null) throws NPE
1117       */
1118      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1119 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1120 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1121 <        l.add(new StringTask());
1122 <        try {
1123 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1124 <            shouldThrow();
1125 <        } catch (NullPointerException success) {
1126 <        } finally {
1146 <            joinPool(e);
1119 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1120 >        try (PoolCleaner cleaner = cleaner(e)) {
1121 >            List<Callable<String>> l = new ArrayList<>();
1122 >            l.add(new StringTask());
1123 >            try {
1124 >                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1125 >                shouldThrow();
1126 >            } catch (NullPointerException success) {}
1127          }
1128      }
1129  
# Line 1151 | Line 1131 | public class ScheduledExecutorTest exten
1131       * timed invokeAll(empty collection) returns empty collection
1132       */
1133      public void testTimedInvokeAll2() throws Exception {
1134 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1135 <        try {
1136 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1134 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1135 >        try (PoolCleaner cleaner = cleaner(e)) {
1136 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1137 >                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1138              assertTrue(r.isEmpty());
1158        } finally {
1159            joinPool(e);
1139          }
1140      }
1141  
# Line 1164 | Line 1143 | public class ScheduledExecutorTest exten
1143       * timed invokeAll(c) throws NPE if c has null elements
1144       */
1145      public void testTimedInvokeAll3() throws Exception {
1146 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1147 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1148 <        l.add(new StringTask());
1149 <        l.add(null);
1150 <        try {
1151 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1152 <            shouldThrow();
1153 <        } catch (NullPointerException success) {
1154 <        } finally {
1176 <            joinPool(e);
1146 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1147 >        try (PoolCleaner cleaner = cleaner(e)) {
1148 >            List<Callable<String>> l = new ArrayList<>();
1149 >            l.add(new StringTask());
1150 >            l.add(null);
1151 >            try {
1152 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1153 >                shouldThrow();
1154 >            } catch (NullPointerException success) {}
1155          }
1156      }
1157  
# Line 1181 | Line 1159 | public class ScheduledExecutorTest exten
1159       * get of element of invokeAll(c) throws exception on failed task
1160       */
1161      public void testTimedInvokeAll4() throws Exception {
1162 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1164 <        l.add(new NPETask());
1165 <        List<Future<String>> futures =
1166 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1167 <        assertEquals(1, futures.size());
1168 <        try {
1169 <            futures.get(0).get();
1170 <            shouldThrow();
1171 <        } catch (ExecutionException success) {
1172 <            assertTrue(success.getCause() instanceof NullPointerException);
1173 <        } finally {
1174 <            joinPool(e);
1162 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163 >        try (PoolCleaner cleaner = cleaner(e)) {
1164 >            List<Callable<String>> l = new ArrayList<>();
1165 >            l.add(new NPETask());
1166 >            List<Future<String>> futures =
1167 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1168 >            assertEquals(1, futures.size());
1169 >            try {
1170 >                futures.get(0).get();
1171 >                shouldThrow();
1172 >            } catch (ExecutionException success) {
1173 >                assertTrue(success.getCause() instanceof NullPointerException);
1174 >            }
1175          }
1176      }
1177  
# Line 1201 | Line 1179 | public class ScheduledExecutorTest exten
1179       * timed invokeAll(c) returns results of all completed tasks
1180       */
1181      public void testTimedInvokeAll5() throws Exception {
1182 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1183 <        try {
1184 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1182 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1183 >        try (PoolCleaner cleaner = cleaner(e)) {
1184 >            List<Callable<String>> l = new ArrayList<>();
1185              l.add(new StringTask());
1186              l.add(new StringTask());
1187              List<Future<String>> futures =
1188 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1188 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1189              assertEquals(2, futures.size());
1190              for (Future<String> future : futures)
1191                  assertSame(TEST_STRING, future.get());
1214        } finally {
1215            joinPool(e);
1192          }
1193      }
1194  
# Line 1220 | Line 1196 | public class ScheduledExecutorTest exten
1196       * timed invokeAll(c) cancels tasks not completed by timeout
1197       */
1198      public void testTimedInvokeAll6() throws Exception {
1199 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1200 <        try {
1201 <            for (long timeout = timeoutMillis();;) {
1199 >        for (long timeout = timeoutMillis();;) {
1200 >            final CountDownLatch done = new CountDownLatch(1);
1201 >            final Callable<String> waiter = new CheckedCallable<String>() {
1202 >                public String realCall() {
1203 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1204 >                    catch (InterruptedException ok) {}
1205 >                    return "1"; }};
1206 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1207 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1208                  List<Callable<String>> tasks = new ArrayList<>();
1209                  tasks.add(new StringTask("0"));
1210 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1210 >                tasks.add(waiter);
1211                  tasks.add(new StringTask("2"));
1212                  long startTime = System.nanoTime();
1213                  List<Future<String>> futures =
1214 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1214 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1215                  assertEquals(tasks.size(), futures.size());
1216                  assertTrue(millisElapsedSince(startTime) >= timeout);
1217                  for (Future future : futures)
# Line 1245 | Line 1227 | public class ScheduledExecutorTest exten
1227                          fail("expected exactly one task to be cancelled");
1228                  }
1229              }
1230 <        } finally {
1231 <            joinPool(e);
1230 >        }
1231 >    }
1232 >
1233 >    /**
1234 >     * A fixed delay task with overflowing period should not prevent a
1235 >     * one-shot task from executing.
1236 >     * https://bugs.openjdk.java.net/browse/JDK-8051859
1237 >     */
1238 >    public void testScheduleWithFixedDelay_overflow() throws Exception {
1239 >        final CountDownLatch delayedDone = new CountDownLatch(1);
1240 >        final CountDownLatch immediateDone = new CountDownLatch(1);
1241 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1242 >        try (PoolCleaner cleaner = cleaner(p)) {
1243 >            final Runnable immediate = new Runnable() { public void run() {
1244 >                immediateDone.countDown();
1245 >            }};
1246 >            final Runnable delayed = new Runnable() { public void run() {
1247 >                delayedDone.countDown();
1248 >                p.submit(immediate);
1249 >            }};
1250 >            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1251 >            await(delayedDone);
1252 >            await(immediateDone);
1253          }
1254      }
1255  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines