ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.80
Committed: Mon Feb 22 23:16:06 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.79: +47 -21 lines
Log Message:
make tests more robust against slow VMs; fix for JDK-8150319: ScheduledExecutorTest:testFixedDelaySequence timeout with slow VMs

File Contents

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