ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.89
Committed: Tue Mar 28 18:13:10 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.88: +116 -55 lines
Log Message:
fix 8177632 and 8176254

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