ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java
Revision: 1.52
Committed: Sun Oct 4 01:18:25 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.51: +20 -9 lines
Log Message:
improve testPrestartCoreThread

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4 jsr166 1.25 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.2 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9 jsr166 1.9 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 jsr166 1.36 import static java.util.concurrent.TimeUnit.SECONDS;
11 jsr166 1.33
12     import java.util.ArrayList;
13     import java.util.List;
14     import java.util.concurrent.ArrayBlockingQueue;
15     import java.util.concurrent.BlockingQueue;
16     import java.util.concurrent.Callable;
17 jsr166 1.39 import java.util.concurrent.CancellationException;
18 jsr166 1.33 import java.util.concurrent.CountDownLatch;
19     import java.util.concurrent.ExecutionException;
20     import java.util.concurrent.Executors;
21     import java.util.concurrent.ExecutorService;
22     import java.util.concurrent.Future;
23     import java.util.concurrent.FutureTask;
24     import java.util.concurrent.LinkedBlockingQueue;
25     import java.util.concurrent.RejectedExecutionException;
26     import java.util.concurrent.RejectedExecutionHandler;
27     import java.util.concurrent.RunnableFuture;
28     import java.util.concurrent.SynchronousQueue;
29     import java.util.concurrent.ThreadFactory;
30     import java.util.concurrent.ThreadPoolExecutor;
31     import java.util.concurrent.TimeoutException;
32     import java.util.concurrent.TimeUnit;
33 jsr166 1.41 import java.util.concurrent.atomic.AtomicInteger;
34 jsr166 1.31 import java.util.concurrent.locks.Condition;
35     import java.util.concurrent.locks.ReentrantLock;
36 jsr166 1.33
37     import junit.framework.Test;
38     import junit.framework.TestSuite;
39 dl 1.1
40     public class ThreadPoolExecutorSubclassTest extends JSR166TestCase {
41     public static void main(String[] args) {
42 jsr166 1.35 main(suite(), args);
43 dl 1.1 }
44     public static Test suite() {
45 jsr166 1.6 return new TestSuite(ThreadPoolExecutorSubclassTest.class);
46 dl 1.1 }
47    
48     static class CustomTask<V> implements RunnableFuture<V> {
49     final Callable<V> callable;
50     final ReentrantLock lock = new ReentrantLock();
51     final Condition cond = lock.newCondition();
52     boolean done;
53     boolean cancelled;
54     V result;
55     Thread thread;
56     Exception exception;
57 jsr166 1.6 CustomTask(Callable<V> c) {
58     if (c == null) throw new NullPointerException();
59     callable = c;
60     }
61     CustomTask(final Runnable r, final V res) {
62     if (r == null) throw new NullPointerException();
63     callable = new Callable<V>() {
64 jsr166 1.34 public V call() throws Exception { r.run(); return res; }};
65 dl 1.1 }
66     public boolean isDone() {
67     lock.lock(); try { return done; } finally { lock.unlock() ; }
68     }
69     public boolean isCancelled() {
70     lock.lock(); try { return cancelled; } finally { lock.unlock() ; }
71     }
72     public boolean cancel(boolean mayInterrupt) {
73     lock.lock();
74     try {
75     if (!done) {
76     cancelled = true;
77     done = true;
78 jsr166 1.2 if (mayInterrupt && thread != null)
79 dl 1.1 thread.interrupt();
80     return true;
81     }
82     return false;
83     }
84     finally { lock.unlock() ; }
85     }
86     public void run() {
87     lock.lock();
88     try {
89 jsr166 1.22 if (done)
90     return;
91     thread = Thread.currentThread();
92 dl 1.1 }
93     finally { lock.unlock() ; }
94     V v = null;
95     Exception e = null;
96     try {
97     v = callable.call();
98     }
99 jsr166 1.3 catch (Exception ex) {
100 dl 1.1 e = ex;
101     }
102     lock.lock();
103     try {
104 jsr166 1.44 if (!done) {
105     result = v;
106     exception = e;
107     done = true;
108     thread = null;
109     cond.signalAll();
110     }
111 dl 1.1 }
112     finally { lock.unlock(); }
113     }
114     public V get() throws InterruptedException, ExecutionException {
115     lock.lock();
116     try {
117 jsr166 1.2 while (!done)
118 dl 1.1 cond.await();
119 jsr166 1.44 if (cancelled)
120     throw new CancellationException();
121 dl 1.1 if (exception != null)
122     throw new ExecutionException(exception);
123     return result;
124     }
125     finally { lock.unlock(); }
126     }
127     public V get(long timeout, TimeUnit unit)
128 jsr166 1.4 throws InterruptedException, ExecutionException, TimeoutException {
129 dl 1.1 long nanos = unit.toNanos(timeout);
130     lock.lock();
131     try {
132 jsr166 1.44 while (!done) {
133 jsr166 1.47 if (nanos <= 0L)
134 dl 1.1 throw new TimeoutException();
135     nanos = cond.awaitNanos(nanos);
136     }
137 jsr166 1.44 if (cancelled)
138     throw new CancellationException();
139 dl 1.1 if (exception != null)
140     throw new ExecutionException(exception);
141     return result;
142     }
143     finally { lock.unlock(); }
144     }
145 jsr166 1.2 }
146    
147 dl 1.1 static class CustomTPE extends ThreadPoolExecutor {
148     protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
149     return new CustomTask<V>(c);
150     }
151     protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
152     return new CustomTask<V>(r, v);
153 jsr166 1.2 }
154    
155 dl 1.1 CustomTPE(int corePoolSize,
156     int maximumPoolSize,
157     long keepAliveTime,
158     TimeUnit unit,
159     BlockingQueue<Runnable> workQueue) {
160 jsr166 1.2 super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
161 dl 1.1 workQueue);
162     }
163     CustomTPE(int corePoolSize,
164     int maximumPoolSize,
165     long keepAliveTime,
166     TimeUnit unit,
167     BlockingQueue<Runnable> workQueue,
168     ThreadFactory threadFactory) {
169     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
170     threadFactory);
171     }
172    
173     CustomTPE(int corePoolSize,
174     int maximumPoolSize,
175     long keepAliveTime,
176     TimeUnit unit,
177     BlockingQueue<Runnable> workQueue,
178     RejectedExecutionHandler handler) {
179     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
180     handler);
181     }
182     CustomTPE(int corePoolSize,
183     int maximumPoolSize,
184     long keepAliveTime,
185     TimeUnit unit,
186     BlockingQueue<Runnable> workQueue,
187     ThreadFactory threadFactory,
188     RejectedExecutionHandler handler) {
189 jsr166 1.2 super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
190 dl 1.1 workQueue, threadFactory, handler);
191     }
192    
193 jsr166 1.30 final CountDownLatch beforeCalled = new CountDownLatch(1);
194     final CountDownLatch afterCalled = new CountDownLatch(1);
195     final CountDownLatch terminatedCalled = new CountDownLatch(1);
196    
197 dl 1.1 public CustomTPE() {
198 jsr166 1.9 super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
199 dl 1.1 }
200     protected void beforeExecute(Thread t, Runnable r) {
201 jsr166 1.30 beforeCalled.countDown();
202 dl 1.1 }
203     protected void afterExecute(Runnable r, Throwable t) {
204 jsr166 1.30 afterCalled.countDown();
205 dl 1.1 }
206     protected void terminated() {
207 jsr166 1.30 terminatedCalled.countDown();
208 dl 1.1 }
209 jsr166 1.2
210 jsr166 1.30 public boolean beforeCalled() {
211     return beforeCalled.getCount() == 0;
212     }
213     public boolean afterCalled() {
214     return afterCalled.getCount() == 0;
215     }
216     public boolean terminatedCalled() {
217     return terminatedCalled.getCount() == 0;
218     }
219 dl 1.1 }
220    
221 jsr166 1.4 static class FailingThreadFactory implements ThreadFactory {
222 dl 1.1 int calls = 0;
223 jsr166 1.4 public Thread newThread(Runnable r) {
224 dl 1.1 if (++calls > 1) return null;
225     return new Thread(r);
226 jsr166 1.2 }
227 dl 1.1 }
228 jsr166 1.2
229 dl 1.1 /**
230 jsr166 1.19 * execute successfully executes a runnable
231 dl 1.1 */
232 jsr166 1.5 public void testExecute() throws InterruptedException {
233 jsr166 1.50 final ThreadPoolExecutor p =
234     new CustomTPE(1, 1,
235     2 * LONG_DELAY_MS, MILLISECONDS,
236     new ArrayBlockingQueue<Runnable>(10));
237 jsr166 1.51 try (PoolCleaner cleaner = cleaner(p)) {
238 jsr166 1.48 final CountDownLatch done = new CountDownLatch(1);
239     final Runnable task = new CheckedRunnable() {
240 jsr166 1.50 public void realRun() { done.countDown(); }};
241 jsr166 1.21 p.execute(task);
242 jsr166 1.48 assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
243 jsr166 1.2 }
244 dl 1.1 }
245    
246     /**
247 jsr166 1.19 * getActiveCount increases but doesn't overestimate, when a
248     * thread becomes active
249 dl 1.1 */
250 jsr166 1.5 public void testGetActiveCount() throws InterruptedException {
251 jsr166 1.21 final ThreadPoolExecutor p =
252     new CustomTPE(2, 2,
253     LONG_DELAY_MS, MILLISECONDS,
254     new ArrayBlockingQueue<Runnable>(10));
255     final CountDownLatch threadStarted = new CountDownLatch(1);
256     final CountDownLatch done = new CountDownLatch(1);
257 jsr166 1.51 try (PoolCleaner cleaner = cleaner(p)) {
258 jsr166 1.21 assertEquals(0, p.getActiveCount());
259     p.execute(new CheckedRunnable() {
260     public void realRun() throws InterruptedException {
261     threadStarted.countDown();
262     assertEquals(1, p.getActiveCount());
263     done.await();
264     }});
265     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
266     assertEquals(1, p.getActiveCount());
267     done.countDown();
268     }
269 dl 1.1 }
270    
271     /**
272 jsr166 1.19 * prestartCoreThread starts a thread if under corePoolSize, else doesn't
273 dl 1.1 */
274     public void testPrestartCoreThread() {
275 jsr166 1.52 ThreadPoolExecutor p =
276     new CustomTPE(2, 6,
277     LONG_DELAY_MS, MILLISECONDS,
278     new ArrayBlockingQueue<Runnable>(10));
279     try (PoolCleaner cleaner = cleaner(p)) {
280     assertEquals(0, p.getPoolSize());
281     assertTrue(p.prestartCoreThread());
282     assertEquals(1, p.getPoolSize());
283     assertTrue(p.prestartCoreThread());
284     assertEquals(2, p.getPoolSize());
285     assertFalse(p.prestartCoreThread());
286     assertEquals(2, p.getPoolSize());
287     p.setCorePoolSize(4);
288     assertTrue(p.prestartCoreThread());
289     assertEquals(3, p.getPoolSize());
290     assertTrue(p.prestartCoreThread());
291     assertEquals(4, p.getPoolSize());
292     assertFalse(p.prestartCoreThread());
293     assertEquals(4, p.getPoolSize());
294     }
295 dl 1.1 }
296    
297     /**
298 jsr166 1.19 * prestartAllCoreThreads starts all corePoolSize threads
299 dl 1.1 */
300     public void testPrestartAllCoreThreads() {
301 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
302     assertEquals(0, p.getPoolSize());
303     p.prestartAllCoreThreads();
304     assertEquals(2, p.getPoolSize());
305     p.prestartAllCoreThreads();
306     assertEquals(2, p.getPoolSize());
307     joinPool(p);
308 dl 1.1 }
309 jsr166 1.2
310 dl 1.1 /**
311 jsr166 1.19 * getCompletedTaskCount increases, but doesn't overestimate,
312     * when tasks complete
313 dl 1.1 */
314 jsr166 1.5 public void testGetCompletedTaskCount() throws InterruptedException {
315 jsr166 1.21 final ThreadPoolExecutor p =
316     new CustomTPE(2, 2,
317     LONG_DELAY_MS, MILLISECONDS,
318     new ArrayBlockingQueue<Runnable>(10));
319     final CountDownLatch threadStarted = new CountDownLatch(1);
320     final CountDownLatch threadProceed = new CountDownLatch(1);
321     final CountDownLatch threadDone = new CountDownLatch(1);
322     try {
323     assertEquals(0, p.getCompletedTaskCount());
324     p.execute(new CheckedRunnable() {
325     public void realRun() throws InterruptedException {
326     threadStarted.countDown();
327     assertEquals(0, p.getCompletedTaskCount());
328     threadProceed.await();
329     threadDone.countDown();
330     }});
331 jsr166 1.30 await(threadStarted);
332 jsr166 1.21 assertEquals(0, p.getCompletedTaskCount());
333     threadProceed.countDown();
334     threadDone.await();
335 jsr166 1.30 long startTime = System.nanoTime();
336     while (p.getCompletedTaskCount() != 1) {
337     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
338     fail("timed out");
339     Thread.yield();
340     }
341 jsr166 1.21 } finally {
342     joinPool(p);
343     }
344 dl 1.1 }
345 jsr166 1.2
346 dl 1.1 /**
347 jsr166 1.19 * getCorePoolSize returns size given in constructor if not otherwise set
348 dl 1.1 */
349     public void testGetCorePoolSize() {
350 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
351     assertEquals(1, p.getCorePoolSize());
352     joinPool(p);
353 dl 1.1 }
354 jsr166 1.2
355 dl 1.1 /**
356 jsr166 1.19 * getKeepAliveTime returns value given in constructor if not otherwise set
357 dl 1.1 */
358     public void testGetKeepAliveTime() {
359 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
360 jsr166 1.38 assertEquals(1, p.getKeepAliveTime(SECONDS));
361 jsr166 1.21 joinPool(p);
362 dl 1.1 }
363    
364 jsr166 1.2 /**
365 dl 1.1 * getThreadFactory returns factory in constructor if not set
366     */
367     public void testGetThreadFactory() {
368     ThreadFactory tf = new SimpleThreadFactory();
369 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), tf, new NoOpREHandler());
370 dl 1.1 assertSame(tf, p.getThreadFactory());
371     joinPool(p);
372     }
373    
374 jsr166 1.2 /**
375 dl 1.1 * setThreadFactory sets the thread factory returned by getThreadFactory
376     */
377     public void testSetThreadFactory() {
378 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
379 dl 1.1 ThreadFactory tf = new SimpleThreadFactory();
380     p.setThreadFactory(tf);
381     assertSame(tf, p.getThreadFactory());
382     joinPool(p);
383     }
384    
385 jsr166 1.2 /**
386 dl 1.1 * setThreadFactory(null) throws NPE
387     */
388     public void testSetThreadFactoryNull() {
389 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
390 dl 1.1 try {
391     p.setThreadFactory(null);
392     shouldThrow();
393     } catch (NullPointerException success) {
394     } finally {
395     joinPool(p);
396     }
397     }
398    
399 jsr166 1.2 /**
400 dl 1.1 * getRejectedExecutionHandler returns handler in constructor if not set
401     */
402     public void testGetRejectedExecutionHandler() {
403     RejectedExecutionHandler h = new NoOpREHandler();
404 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), h);
405 dl 1.1 assertSame(h, p.getRejectedExecutionHandler());
406     joinPool(p);
407     }
408    
409 jsr166 1.2 /**
410 dl 1.1 * setRejectedExecutionHandler sets the handler returned by
411     * getRejectedExecutionHandler
412     */
413     public void testSetRejectedExecutionHandler() {
414 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
415 dl 1.1 RejectedExecutionHandler h = new NoOpREHandler();
416     p.setRejectedExecutionHandler(h);
417     assertSame(h, p.getRejectedExecutionHandler());
418     joinPool(p);
419     }
420    
421 jsr166 1.2 /**
422 dl 1.1 * setRejectedExecutionHandler(null) throws NPE
423     */
424     public void testSetRejectedExecutionHandlerNull() {
425 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
426 dl 1.1 try {
427     p.setRejectedExecutionHandler(null);
428     shouldThrow();
429     } catch (NullPointerException success) {
430     } finally {
431     joinPool(p);
432     }
433     }
434    
435     /**
436 jsr166 1.19 * getLargestPoolSize increases, but doesn't overestimate, when
437     * multiple threads active
438 dl 1.1 */
439 jsr166 1.5 public void testGetLargestPoolSize() throws InterruptedException {
440 jsr166 1.21 final int THREADS = 3;
441     final ThreadPoolExecutor p =
442     new CustomTPE(THREADS, THREADS,
443     LONG_DELAY_MS, MILLISECONDS,
444     new ArrayBlockingQueue<Runnable>(10));
445     final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
446     final CountDownLatch done = new CountDownLatch(1);
447     try {
448     assertEquals(0, p.getLargestPoolSize());
449     for (int i = 0; i < THREADS; i++)
450     p.execute(new CheckedRunnable() {
451     public void realRun() throws InterruptedException {
452     threadsStarted.countDown();
453     done.await();
454     assertEquals(THREADS, p.getLargestPoolSize());
455     }});
456     assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
457     assertEquals(THREADS, p.getLargestPoolSize());
458     } finally {
459     done.countDown();
460     joinPool(p);
461     assertEquals(THREADS, p.getLargestPoolSize());
462     }
463 dl 1.1 }
464 jsr166 1.2
465 dl 1.1 /**
466 jsr166 1.19 * getMaximumPoolSize returns value given in constructor if not
467     * otherwise set
468 dl 1.1 */
469     public void testGetMaximumPoolSize() {
470 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
471     assertEquals(2, p.getMaximumPoolSize());
472     joinPool(p);
473 dl 1.1 }
474 jsr166 1.2
475 dl 1.1 /**
476 jsr166 1.19 * getPoolSize increases, but doesn't overestimate, when threads
477     * become active
478 dl 1.1 */
479 jsr166 1.21 public void testGetPoolSize() throws InterruptedException {
480     final ThreadPoolExecutor p =
481     new CustomTPE(1, 1,
482     LONG_DELAY_MS, MILLISECONDS,
483     new ArrayBlockingQueue<Runnable>(10));
484     final CountDownLatch threadStarted = new CountDownLatch(1);
485     final CountDownLatch done = new CountDownLatch(1);
486     try {
487     assertEquals(0, p.getPoolSize());
488     p.execute(new CheckedRunnable() {
489     public void realRun() throws InterruptedException {
490     threadStarted.countDown();
491     assertEquals(1, p.getPoolSize());
492     done.await();
493     }});
494     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
495     assertEquals(1, p.getPoolSize());
496     } finally {
497     done.countDown();
498     joinPool(p);
499     }
500 dl 1.1 }
501 jsr166 1.2
502 dl 1.1 /**
503 jsr166 1.19 * getTaskCount increases, but doesn't overestimate, when tasks submitted
504 dl 1.1 */
505 jsr166 1.5 public void testGetTaskCount() throws InterruptedException {
506 jsr166 1.21 final ThreadPoolExecutor p =
507     new CustomTPE(1, 1,
508     LONG_DELAY_MS, MILLISECONDS,
509     new ArrayBlockingQueue<Runnable>(10));
510     final CountDownLatch threadStarted = new CountDownLatch(1);
511     final CountDownLatch done = new CountDownLatch(1);
512     try {
513     assertEquals(0, p.getTaskCount());
514     p.execute(new CheckedRunnable() {
515     public void realRun() throws InterruptedException {
516     threadStarted.countDown();
517     assertEquals(1, p.getTaskCount());
518     done.await();
519     }});
520     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
521     assertEquals(1, p.getTaskCount());
522     } finally {
523     done.countDown();
524     joinPool(p);
525     }
526 dl 1.1 }
527 jsr166 1.2
528 dl 1.1 /**
529 jsr166 1.28 * isShutdown is false before shutdown, true after
530 dl 1.1 */
531     public void testIsShutdown() {
532 jsr166 1.2
533 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
534     assertFalse(p.isShutdown());
535     try { p.shutdown(); } catch (SecurityException ok) { return; }
536     assertTrue(p.isShutdown());
537     joinPool(p);
538 dl 1.1 }
539    
540     /**
541 jsr166 1.19 * isTerminated is false before termination, true after
542 dl 1.1 */
543 jsr166 1.5 public void testIsTerminated() throws InterruptedException {
544 jsr166 1.21 final ThreadPoolExecutor p =
545     new CustomTPE(1, 1,
546     LONG_DELAY_MS, MILLISECONDS,
547     new ArrayBlockingQueue<Runnable>(10));
548     final CountDownLatch threadStarted = new CountDownLatch(1);
549     final CountDownLatch done = new CountDownLatch(1);
550     try {
551     assertFalse(p.isTerminating());
552     p.execute(new CheckedRunnable() {
553     public void realRun() throws InterruptedException {
554 jsr166 1.24 assertFalse(p.isTerminating());
555 jsr166 1.21 threadStarted.countDown();
556     done.await();
557     }});
558     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
559     assertFalse(p.isTerminating());
560     done.countDown();
561     } finally {
562     try { p.shutdown(); } catch (SecurityException ok) { return; }
563     }
564     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
565     assertTrue(p.isTerminated());
566     assertFalse(p.isTerminating());
567 dl 1.1 }
568    
569     /**
570 jsr166 1.19 * isTerminating is not true when running or when terminated
571 dl 1.1 */
572 jsr166 1.5 public void testIsTerminating() throws InterruptedException {
573 jsr166 1.21 final ThreadPoolExecutor p =
574     new CustomTPE(1, 1,
575     LONG_DELAY_MS, MILLISECONDS,
576     new ArrayBlockingQueue<Runnable>(10));
577     final CountDownLatch threadStarted = new CountDownLatch(1);
578     final CountDownLatch done = new CountDownLatch(1);
579     try {
580     assertFalse(p.isTerminating());
581     p.execute(new CheckedRunnable() {
582     public void realRun() throws InterruptedException {
583 jsr166 1.23 assertFalse(p.isTerminating());
584 jsr166 1.21 threadStarted.countDown();
585     done.await();
586     }});
587     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
588     assertFalse(p.isTerminating());
589     done.countDown();
590     } finally {
591     try { p.shutdown(); } catch (SecurityException ok) { return; }
592     }
593     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
594     assertTrue(p.isTerminated());
595     assertFalse(p.isTerminating());
596 dl 1.1 }
597    
598     /**
599     * getQueue returns the work queue, which contains queued tasks
600     */
601 jsr166 1.5 public void testGetQueue() throws InterruptedException {
602 jsr166 1.21 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
603     final ThreadPoolExecutor p =
604     new CustomTPE(1, 1,
605     LONG_DELAY_MS, MILLISECONDS,
606     q);
607     final CountDownLatch threadStarted = new CountDownLatch(1);
608     final CountDownLatch done = new CountDownLatch(1);
609     try {
610     FutureTask[] tasks = new FutureTask[5];
611     for (int i = 0; i < tasks.length; i++) {
612     Callable task = new CheckedCallable<Boolean>() {
613     public Boolean realCall() throws InterruptedException {
614     threadStarted.countDown();
615     assertSame(q, p.getQueue());
616     done.await();
617     return Boolean.TRUE;
618     }};
619     tasks[i] = new FutureTask(task);
620     p.execute(tasks[i]);
621     }
622     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
623     assertSame(q, p.getQueue());
624     assertFalse(q.contains(tasks[0]));
625     assertTrue(q.contains(tasks[tasks.length - 1]));
626     assertEquals(tasks.length - 1, q.size());
627 dl 1.1 } finally {
628 jsr166 1.21 done.countDown();
629     joinPool(p);
630 dl 1.1 }
631     }
632    
633     /**
634     * remove(task) removes queued task, and fails to remove active task
635     */
636 jsr166 1.5 public void testRemove() throws InterruptedException {
637 dl 1.1 BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
638 jsr166 1.21 final ThreadPoolExecutor p =
639     new CustomTPE(1, 1,
640     LONG_DELAY_MS, MILLISECONDS,
641     q);
642     Runnable[] tasks = new Runnable[6];
643     final CountDownLatch threadStarted = new CountDownLatch(1);
644     final CountDownLatch done = new CountDownLatch(1);
645     try {
646     for (int i = 0; i < tasks.length; i++) {
647     tasks[i] = new CheckedRunnable() {
648     public void realRun() throws InterruptedException {
649     threadStarted.countDown();
650     done.await();
651     }};
652     p.execute(tasks[i]);
653     }
654     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
655     assertFalse(p.remove(tasks[0]));
656 dl 1.1 assertTrue(q.contains(tasks[4]));
657     assertTrue(q.contains(tasks[3]));
658 jsr166 1.21 assertTrue(p.remove(tasks[4]));
659     assertFalse(p.remove(tasks[4]));
660 dl 1.1 assertFalse(q.contains(tasks[4]));
661     assertTrue(q.contains(tasks[3]));
662 jsr166 1.21 assertTrue(p.remove(tasks[3]));
663 dl 1.1 assertFalse(q.contains(tasks[3]));
664     } finally {
665 jsr166 1.21 done.countDown();
666     joinPool(p);
667 dl 1.1 }
668     }
669    
670     /**
671 jsr166 1.19 * purge removes cancelled tasks from the queue
672 dl 1.1 */
673 jsr166 1.21 public void testPurge() throws InterruptedException {
674     final CountDownLatch threadStarted = new CountDownLatch(1);
675     final CountDownLatch done = new CountDownLatch(1);
676     final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
677     final ThreadPoolExecutor p =
678     new CustomTPE(1, 1,
679     LONG_DELAY_MS, MILLISECONDS,
680     q);
681 dl 1.1 FutureTask[] tasks = new FutureTask[5];
682 jsr166 1.21 try {
683     for (int i = 0; i < tasks.length; i++) {
684     Callable task = new CheckedCallable<Boolean>() {
685     public Boolean realCall() throws InterruptedException {
686     threadStarted.countDown();
687     done.await();
688     return Boolean.TRUE;
689     }};
690     tasks[i] = new FutureTask(task);
691     p.execute(tasks[i]);
692     }
693     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
694     assertEquals(tasks.length, p.getTaskCount());
695     assertEquals(tasks.length - 1, q.size());
696     assertEquals(1L, p.getActiveCount());
697     assertEquals(0L, p.getCompletedTaskCount());
698     tasks[4].cancel(true);
699     tasks[3].cancel(false);
700     p.purge();
701     assertEquals(tasks.length - 3, q.size());
702     assertEquals(tasks.length - 2, p.getTaskCount());
703     p.purge(); // Nothing to do
704     assertEquals(tasks.length - 3, q.size());
705     assertEquals(tasks.length - 2, p.getTaskCount());
706     } finally {
707     done.countDown();
708     joinPool(p);
709     }
710 dl 1.1 }
711    
712     /**
713 jsr166 1.40 * shutdownNow returns a list containing tasks that were not run,
714     * and those tasks are drained from the queue
715 dl 1.1 */
716 jsr166 1.41 public void testShutdownNow() throws InterruptedException {
717     final int poolSize = 2;
718     final int count = 5;
719     final AtomicInteger ran = new AtomicInteger(0);
720     ThreadPoolExecutor p =
721     new CustomTPE(poolSize, poolSize, LONG_DELAY_MS, MILLISECONDS,
722     new ArrayBlockingQueue<Runnable>(10));
723     CountDownLatch threadsStarted = new CountDownLatch(poolSize);
724 jsr166 1.43 Runnable waiter = new CheckedRunnable() { public void realRun() {
725 jsr166 1.41 threadsStarted.countDown();
726 dl 1.1 try {
727 jsr166 1.41 MILLISECONDS.sleep(2 * LONG_DELAY_MS);
728     } catch (InterruptedException success) {}
729     ran.getAndIncrement();
730     }};
731     for (int i = 0; i < count; i++)
732     p.execute(waiter);
733     assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
734 jsr166 1.42 assertEquals(poolSize, p.getActiveCount());
735     assertEquals(0, p.getCompletedTaskCount());
736 jsr166 1.41 final List<Runnable> queuedTasks;
737     try {
738     queuedTasks = p.shutdownNow();
739     } catch (SecurityException ok) {
740     return; // Allowed in case test doesn't have privs
741 dl 1.1 }
742 jsr166 1.21 assertTrue(p.isShutdown());
743 jsr166 1.40 assertTrue(p.getQueue().isEmpty());
744 jsr166 1.41 assertEquals(count - poolSize, queuedTasks.size());
745     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
746     assertTrue(p.isTerminated());
747     assertEquals(poolSize, ran.get());
748 jsr166 1.42 assertEquals(poolSize, p.getCompletedTaskCount());
749 dl 1.1 }
750    
751     // Exception Tests
752    
753 jsr166 1.2 /**
754     * Constructor throws if corePoolSize argument is less than zero
755 dl 1.1 */
756     public void testConstructor1() {
757     try {
758 jsr166 1.36 new CustomTPE(-1, 1, 1L, SECONDS,
759     new ArrayBlockingQueue<Runnable>(10));
760 dl 1.1 shouldThrow();
761 jsr166 1.5 } catch (IllegalArgumentException success) {}
762 dl 1.1 }
763 jsr166 1.2
764     /**
765     * Constructor throws if maximumPoolSize is less than zero
766 dl 1.1 */
767     public void testConstructor2() {
768     try {
769 jsr166 1.36 new CustomTPE(1, -1, 1L, SECONDS,
770     new ArrayBlockingQueue<Runnable>(10));
771 dl 1.1 shouldThrow();
772 jsr166 1.5 } catch (IllegalArgumentException success) {}
773 dl 1.1 }
774 jsr166 1.2
775     /**
776     * Constructor throws if maximumPoolSize is equal to zero
777 dl 1.1 */
778     public void testConstructor3() {
779     try {
780 jsr166 1.36 new CustomTPE(1, 0, 1L, SECONDS,
781     new ArrayBlockingQueue<Runnable>(10));
782 dl 1.1 shouldThrow();
783 jsr166 1.5 } catch (IllegalArgumentException success) {}
784 dl 1.1 }
785    
786 jsr166 1.2 /**
787     * Constructor throws if keepAliveTime is less than zero
788 dl 1.1 */
789     public void testConstructor4() {
790     try {
791 jsr166 1.36 new CustomTPE(1, 2, -1L, SECONDS,
792     new ArrayBlockingQueue<Runnable>(10));
793 dl 1.1 shouldThrow();
794 jsr166 1.5 } catch (IllegalArgumentException success) {}
795 dl 1.1 }
796    
797 jsr166 1.2 /**
798     * Constructor throws if corePoolSize is greater than the maximumPoolSize
799 dl 1.1 */
800     public void testConstructor5() {
801     try {
802 jsr166 1.36 new CustomTPE(2, 1, 1L, SECONDS,
803     new ArrayBlockingQueue<Runnable>(10));
804 dl 1.1 shouldThrow();
805 jsr166 1.5 } catch (IllegalArgumentException success) {}
806 dl 1.1 }
807 jsr166 1.2
808     /**
809     * Constructor throws if workQueue is set to null
810 dl 1.1 */
811     public void testConstructorNullPointerException() {
812     try {
813 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS, null);
814 dl 1.1 shouldThrow();
815 jsr166 1.5 } catch (NullPointerException success) {}
816 dl 1.1 }
817    
818 jsr166 1.2 /**
819     * Constructor throws if corePoolSize argument is less than zero
820 dl 1.1 */
821     public void testConstructor6() {
822     try {
823 jsr166 1.36 new CustomTPE(-1, 1, 1L, SECONDS,
824     new ArrayBlockingQueue<Runnable>(10),
825     new SimpleThreadFactory());
826 dl 1.1 shouldThrow();
827 jsr166 1.4 } catch (IllegalArgumentException success) {}
828 dl 1.1 }
829 jsr166 1.2
830     /**
831     * Constructor throws if maximumPoolSize is less than zero
832 dl 1.1 */
833     public void testConstructor7() {
834     try {
835 jsr166 1.36 new CustomTPE(1,-1, 1L, SECONDS,
836     new ArrayBlockingQueue<Runnable>(10),
837     new SimpleThreadFactory());
838 dl 1.1 shouldThrow();
839 jsr166 1.5 } catch (IllegalArgumentException success) {}
840 dl 1.1 }
841    
842 jsr166 1.2 /**
843     * Constructor throws if maximumPoolSize is equal to zero
844 dl 1.1 */
845     public void testConstructor8() {
846     try {
847 jsr166 1.36 new CustomTPE(1, 0, 1L, SECONDS,
848     new ArrayBlockingQueue<Runnable>(10),
849     new SimpleThreadFactory());
850 dl 1.1 shouldThrow();
851 jsr166 1.5 } catch (IllegalArgumentException success) {}
852 dl 1.1 }
853    
854 jsr166 1.2 /**
855     * Constructor throws if keepAliveTime is less than zero
856 dl 1.1 */
857     public void testConstructor9() {
858     try {
859 jsr166 1.36 new CustomTPE(1, 2, -1L, SECONDS,
860     new ArrayBlockingQueue<Runnable>(10),
861     new SimpleThreadFactory());
862 dl 1.1 shouldThrow();
863 jsr166 1.5 } catch (IllegalArgumentException success) {}
864 dl 1.1 }
865    
866 jsr166 1.2 /**
867     * Constructor throws if corePoolSize is greater than the maximumPoolSize
868 dl 1.1 */
869     public void testConstructor10() {
870     try {
871 jsr166 1.36 new CustomTPE(2, 1, 1L, SECONDS,
872     new ArrayBlockingQueue<Runnable>(10),
873     new SimpleThreadFactory());
874 dl 1.1 shouldThrow();
875 jsr166 1.5 } catch (IllegalArgumentException success) {}
876 dl 1.1 }
877    
878 jsr166 1.2 /**
879     * Constructor throws if workQueue is set to null
880 dl 1.1 */
881     public void testConstructorNullPointerException2() {
882     try {
883 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS, null, new SimpleThreadFactory());
884 dl 1.1 shouldThrow();
885 jsr166 1.5 } catch (NullPointerException success) {}
886 dl 1.1 }
887    
888 jsr166 1.2 /**
889     * Constructor throws if threadFactory is set to null
890 dl 1.1 */
891     public void testConstructorNullPointerException3() {
892     try {
893 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
894     new ArrayBlockingQueue<Runnable>(10),
895     (ThreadFactory) null);
896 dl 1.1 shouldThrow();
897 jsr166 1.5 } catch (NullPointerException success) {}
898 dl 1.1 }
899 jsr166 1.2
900     /**
901     * Constructor throws if corePoolSize argument is less than zero
902 dl 1.1 */
903     public void testConstructor11() {
904     try {
905 jsr166 1.36 new CustomTPE(-1, 1, 1L, SECONDS,
906     new ArrayBlockingQueue<Runnable>(10),
907     new NoOpREHandler());
908 dl 1.1 shouldThrow();
909 jsr166 1.5 } catch (IllegalArgumentException success) {}
910 dl 1.1 }
911    
912 jsr166 1.2 /**
913     * Constructor throws if maximumPoolSize is less than zero
914 dl 1.1 */
915     public void testConstructor12() {
916     try {
917 jsr166 1.36 new CustomTPE(1, -1, 1L, SECONDS,
918     new ArrayBlockingQueue<Runnable>(10),
919     new NoOpREHandler());
920 dl 1.1 shouldThrow();
921 jsr166 1.5 } catch (IllegalArgumentException success) {}
922 dl 1.1 }
923    
924 jsr166 1.2 /**
925     * Constructor throws if maximumPoolSize is equal to zero
926 dl 1.1 */
927     public void testConstructor13() {
928     try {
929 jsr166 1.36 new CustomTPE(1, 0, 1L, SECONDS,
930     new ArrayBlockingQueue<Runnable>(10),
931     new NoOpREHandler());
932 dl 1.1 shouldThrow();
933 jsr166 1.5 } catch (IllegalArgumentException success) {}
934 dl 1.1 }
935    
936 jsr166 1.2 /**
937     * Constructor throws if keepAliveTime is less than zero
938 dl 1.1 */
939     public void testConstructor14() {
940     try {
941 jsr166 1.36 new CustomTPE(1, 2, -1L, SECONDS,
942     new ArrayBlockingQueue<Runnable>(10),
943     new NoOpREHandler());
944 dl 1.1 shouldThrow();
945 jsr166 1.5 } catch (IllegalArgumentException success) {}
946 dl 1.1 }
947    
948 jsr166 1.2 /**
949     * Constructor throws if corePoolSize is greater than the maximumPoolSize
950 dl 1.1 */
951     public void testConstructor15() {
952     try {
953 jsr166 1.36 new CustomTPE(2, 1, 1L, SECONDS,
954     new ArrayBlockingQueue<Runnable>(10),
955     new NoOpREHandler());
956 dl 1.1 shouldThrow();
957 jsr166 1.5 } catch (IllegalArgumentException success) {}
958 dl 1.1 }
959    
960 jsr166 1.2 /**
961     * Constructor throws if workQueue is set to null
962 dl 1.1 */
963     public void testConstructorNullPointerException4() {
964     try {
965 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
966     null,
967     new NoOpREHandler());
968 dl 1.1 shouldThrow();
969 jsr166 1.5 } catch (NullPointerException success) {}
970 dl 1.1 }
971    
972 jsr166 1.2 /**
973     * Constructor throws if handler is set to null
974 dl 1.1 */
975     public void testConstructorNullPointerException5() {
976     try {
977 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
978     new ArrayBlockingQueue<Runnable>(10),
979     (RejectedExecutionHandler) null);
980 dl 1.1 shouldThrow();
981 jsr166 1.5 } catch (NullPointerException success) {}
982 dl 1.1 }
983    
984 jsr166 1.2 /**
985     * Constructor throws if corePoolSize argument is less than zero
986 dl 1.1 */
987     public void testConstructor16() {
988     try {
989 jsr166 1.36 new CustomTPE(-1, 1, 1L, SECONDS,
990     new ArrayBlockingQueue<Runnable>(10),
991     new SimpleThreadFactory(),
992     new NoOpREHandler());
993 dl 1.1 shouldThrow();
994 jsr166 1.5 } catch (IllegalArgumentException success) {}
995 dl 1.1 }
996    
997 jsr166 1.2 /**
998     * Constructor throws if maximumPoolSize is less than zero
999 dl 1.1 */
1000     public void testConstructor17() {
1001     try {
1002 jsr166 1.36 new CustomTPE(1, -1, 1L, SECONDS,
1003     new ArrayBlockingQueue<Runnable>(10),
1004     new SimpleThreadFactory(),
1005     new NoOpREHandler());
1006 dl 1.1 shouldThrow();
1007 jsr166 1.5 } catch (IllegalArgumentException success) {}
1008 dl 1.1 }
1009    
1010 jsr166 1.2 /**
1011     * Constructor throws if maximumPoolSize is equal to zero
1012 dl 1.1 */
1013     public void testConstructor18() {
1014     try {
1015 jsr166 1.36 new CustomTPE(1, 0, 1L, SECONDS,
1016     new ArrayBlockingQueue<Runnable>(10),
1017     new SimpleThreadFactory(),
1018     new NoOpREHandler());
1019 dl 1.1 shouldThrow();
1020 jsr166 1.5 } catch (IllegalArgumentException success) {}
1021 dl 1.1 }
1022    
1023 jsr166 1.2 /**
1024     * Constructor throws if keepAliveTime is less than zero
1025 dl 1.1 */
1026     public void testConstructor19() {
1027     try {
1028 jsr166 1.36 new CustomTPE(1, 2, -1L, SECONDS,
1029     new ArrayBlockingQueue<Runnable>(10),
1030     new SimpleThreadFactory(),
1031     new NoOpREHandler());
1032 dl 1.1 shouldThrow();
1033 jsr166 1.5 } catch (IllegalArgumentException success) {}
1034 dl 1.1 }
1035    
1036 jsr166 1.2 /**
1037     * Constructor throws if corePoolSize is greater than the maximumPoolSize
1038 dl 1.1 */
1039     public void testConstructor20() {
1040     try {
1041 jsr166 1.36 new CustomTPE(2, 1, 1L, SECONDS,
1042     new ArrayBlockingQueue<Runnable>(10),
1043     new SimpleThreadFactory(),
1044     new NoOpREHandler());
1045 dl 1.1 shouldThrow();
1046 jsr166 1.5 } catch (IllegalArgumentException success) {}
1047 dl 1.1 }
1048    
1049 jsr166 1.2 /**
1050 jsr166 1.20 * Constructor throws if workQueue is null
1051 dl 1.1 */
1052     public void testConstructorNullPointerException6() {
1053     try {
1054 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
1055     null,
1056     new SimpleThreadFactory(),
1057     new NoOpREHandler());
1058 dl 1.1 shouldThrow();
1059 jsr166 1.5 } catch (NullPointerException success) {}
1060 dl 1.1 }
1061    
1062 jsr166 1.2 /**
1063 jsr166 1.20 * Constructor throws if handler is null
1064 dl 1.1 */
1065     public void testConstructorNullPointerException7() {
1066     try {
1067 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
1068     new ArrayBlockingQueue<Runnable>(10),
1069     new SimpleThreadFactory(),
1070     (RejectedExecutionHandler) null);
1071 dl 1.1 shouldThrow();
1072 jsr166 1.5 } catch (NullPointerException success) {}
1073 dl 1.1 }
1074    
1075 jsr166 1.2 /**
1076 jsr166 1.20 * Constructor throws if ThreadFactory is null
1077 dl 1.1 */
1078     public void testConstructorNullPointerException8() {
1079     try {
1080 jsr166 1.36 new CustomTPE(1, 2, 1L, SECONDS,
1081 jsr166 1.21 new ArrayBlockingQueue<Runnable>(10),
1082     (ThreadFactory) null,
1083     new NoOpREHandler());
1084 dl 1.1 shouldThrow();
1085 jsr166 1.5 } catch (NullPointerException success) {}
1086 dl 1.1 }
1087 jsr166 1.2
1088 dl 1.1 /**
1089 jsr166 1.19 * execute throws RejectedExecutionException if saturated.
1090 dl 1.1 */
1091     public void testSaturatedExecute() {
1092 jsr166 1.21 ThreadPoolExecutor p =
1093     new CustomTPE(1, 1,
1094     LONG_DELAY_MS, MILLISECONDS,
1095     new ArrayBlockingQueue<Runnable>(1));
1096     final CountDownLatch done = new CountDownLatch(1);
1097     try {
1098     Runnable task = new CheckedRunnable() {
1099     public void realRun() throws InterruptedException {
1100     done.await();
1101     }};
1102     for (int i = 0; i < 2; ++i)
1103     p.execute(task);
1104     for (int i = 0; i < 2; ++i) {
1105     try {
1106     p.execute(task);
1107     shouldThrow();
1108     } catch (RejectedExecutionException success) {}
1109     assertTrue(p.getTaskCount() <= 2);
1110 dl 1.1 }
1111 jsr166 1.21 } finally {
1112     done.countDown();
1113     joinPool(p);
1114     }
1115 dl 1.1 }
1116    
1117     /**
1118 jsr166 1.19 * executor using CallerRunsPolicy runs task if saturated.
1119 dl 1.1 */
1120     public void testSaturatedExecute2() {
1121     RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
1122 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(1, 1,
1123     LONG_DELAY_MS, MILLISECONDS,
1124     new ArrayBlockingQueue<Runnable>(1),
1125     h);
1126 dl 1.1 try {
1127     TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1128 jsr166 1.21 for (int i = 0; i < tasks.length; ++i)
1129 dl 1.1 tasks[i] = new TrackedNoOpRunnable();
1130     TrackedLongRunnable mr = new TrackedLongRunnable();
1131     p.execute(mr);
1132 jsr166 1.21 for (int i = 0; i < tasks.length; ++i)
1133 dl 1.1 p.execute(tasks[i]);
1134 jsr166 1.21 for (int i = 1; i < tasks.length; ++i)
1135 dl 1.1 assertTrue(tasks[i].done);
1136 jsr166 1.3 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1137 dl 1.1 } finally {
1138     joinPool(p);
1139     }
1140     }
1141    
1142     /**
1143 jsr166 1.19 * executor using DiscardPolicy drops task if saturated.
1144 dl 1.1 */
1145     public void testSaturatedExecute3() {
1146     RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
1147 jsr166 1.21 ThreadPoolExecutor p =
1148     new CustomTPE(1, 1,
1149     LONG_DELAY_MS, MILLISECONDS,
1150     new ArrayBlockingQueue<Runnable>(1),
1151     h);
1152 dl 1.1 try {
1153     TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1154 jsr166 1.21 for (int i = 0; i < tasks.length; ++i)
1155 dl 1.1 tasks[i] = new TrackedNoOpRunnable();
1156     p.execute(new TrackedLongRunnable());
1157 jsr166 1.21 for (TrackedNoOpRunnable task : tasks)
1158     p.execute(task);
1159     for (TrackedNoOpRunnable task : tasks)
1160     assertFalse(task.done);
1161 jsr166 1.3 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1162 dl 1.1 } finally {
1163     joinPool(p);
1164     }
1165     }
1166    
1167     /**
1168 jsr166 1.19 * executor using DiscardOldestPolicy drops oldest task if saturated.
1169 dl 1.1 */
1170     public void testSaturatedExecute4() {
1171     RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
1172 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1173 dl 1.1 try {
1174     p.execute(new TrackedLongRunnable());
1175     TrackedLongRunnable r2 = new TrackedLongRunnable();
1176     p.execute(r2);
1177     assertTrue(p.getQueue().contains(r2));
1178     TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1179     p.execute(r3);
1180     assertFalse(p.getQueue().contains(r2));
1181     assertTrue(p.getQueue().contains(r3));
1182 jsr166 1.3 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1183 dl 1.1 } finally {
1184     joinPool(p);
1185     }
1186     }
1187    
1188     /**
1189 jsr166 1.19 * execute throws RejectedExecutionException if shutdown
1190 dl 1.1 */
1191     public void testRejectedExecutionExceptionOnShutdown() {
1192 jsr166 1.21 ThreadPoolExecutor p =
1193 jsr166 1.9 new CustomTPE(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(1));
1194 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1195 jsr166 1.8 try {
1196 jsr166 1.21 p.execute(new NoOpRunnable());
1197 jsr166 1.8 shouldThrow();
1198     } catch (RejectedExecutionException success) {}
1199 jsr166 1.2
1200 jsr166 1.21 joinPool(p);
1201 dl 1.1 }
1202    
1203     /**
1204 jsr166 1.19 * execute using CallerRunsPolicy drops task on shutdown
1205 dl 1.1 */
1206     public void testCallerRunsOnShutdown() {
1207     RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
1208 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1209 dl 1.1
1210 jsr166 1.3 try { p.shutdown(); } catch (SecurityException ok) { return; }
1211 jsr166 1.8 try {
1212 dl 1.1 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1213 jsr166 1.8 p.execute(r);
1214 dl 1.1 assertFalse(r.done);
1215     } finally {
1216     joinPool(p);
1217     }
1218     }
1219    
1220     /**
1221 jsr166 1.19 * execute using DiscardPolicy drops task on shutdown
1222 dl 1.1 */
1223     public void testDiscardOnShutdown() {
1224     RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
1225 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1226 dl 1.1
1227 jsr166 1.3 try { p.shutdown(); } catch (SecurityException ok) { return; }
1228 jsr166 1.8 try {
1229 dl 1.1 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1230 jsr166 1.8 p.execute(r);
1231 dl 1.1 assertFalse(r.done);
1232     } finally {
1233     joinPool(p);
1234     }
1235     }
1236    
1237     /**
1238 jsr166 1.19 * execute using DiscardOldestPolicy drops task on shutdown
1239 dl 1.1 */
1240     public void testDiscardOldestOnShutdown() {
1241     RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
1242 jsr166 1.9 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1243 dl 1.1
1244 jsr166 1.3 try { p.shutdown(); } catch (SecurityException ok) { return; }
1245 jsr166 1.8 try {
1246 dl 1.1 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1247 jsr166 1.8 p.execute(r);
1248 dl 1.1 assertFalse(r.done);
1249     } finally {
1250     joinPool(p);
1251     }
1252     }
1253    
1254     /**
1255 jsr166 1.18 * execute(null) throws NPE
1256 dl 1.1 */
1257     public void testExecuteNull() {
1258 jsr166 1.37 ThreadPoolExecutor p =
1259     new CustomTPE(1, 2, 1L, SECONDS,
1260     new ArrayBlockingQueue<Runnable>(10));
1261 dl 1.1 try {
1262 jsr166 1.21 p.execute(null);
1263 dl 1.1 shouldThrow();
1264 jsr166 1.8 } catch (NullPointerException success) {}
1265 jsr166 1.2
1266 jsr166 1.21 joinPool(p);
1267 dl 1.1 }
1268 jsr166 1.2
1269 dl 1.1 /**
1270 jsr166 1.19 * setCorePoolSize of negative value throws IllegalArgumentException
1271 dl 1.1 */
1272     public void testCorePoolSizeIllegalArgumentException() {
1273 jsr166 1.21 ThreadPoolExecutor p =
1274 jsr166 1.9 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1275 jsr166 1.8 try {
1276 jsr166 1.21 p.setCorePoolSize(-1);
1277 jsr166 1.8 shouldThrow();
1278     } catch (IllegalArgumentException success) {
1279 dl 1.1 } finally {
1280 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1281 dl 1.1 }
1282 jsr166 1.21 joinPool(p);
1283 jsr166 1.2 }
1284 dl 1.1
1285     /**
1286 jsr166 1.19 * setMaximumPoolSize(int) throws IllegalArgumentException
1287     * if given a value less the core pool size
1288 jsr166 1.2 */
1289 dl 1.1 public void testMaximumPoolSizeIllegalArgumentException() {
1290 jsr166 1.21 ThreadPoolExecutor p =
1291 jsr166 1.10 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1292 dl 1.1 try {
1293 jsr166 1.21 p.setMaximumPoolSize(1);
1294 dl 1.1 shouldThrow();
1295 jsr166 1.4 } catch (IllegalArgumentException success) {
1296 dl 1.1 } finally {
1297 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1298 dl 1.1 }
1299 jsr166 1.21 joinPool(p);
1300 dl 1.1 }
1301 jsr166 1.2
1302 dl 1.1 /**
1303 jsr166 1.19 * setMaximumPoolSize throws IllegalArgumentException
1304     * if given a negative value
1305 dl 1.1 */
1306     public void testMaximumPoolSizeIllegalArgumentException2() {
1307 jsr166 1.21 ThreadPoolExecutor p =
1308 jsr166 1.10 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1309 dl 1.1 try {
1310 jsr166 1.21 p.setMaximumPoolSize(-1);
1311 dl 1.1 shouldThrow();
1312 jsr166 1.4 } catch (IllegalArgumentException success) {
1313 dl 1.1 } finally {
1314 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1315 dl 1.1 }
1316 jsr166 1.21 joinPool(p);
1317 dl 1.1 }
1318 jsr166 1.2
1319 dl 1.1 /**
1320 jsr166 1.19 * setKeepAliveTime throws IllegalArgumentException
1321     * when given a negative value
1322 dl 1.1 */
1323     public void testKeepAliveTimeIllegalArgumentException() {
1324 jsr166 1.21 ThreadPoolExecutor p =
1325 jsr166 1.10 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1326 jsr166 1.2
1327 jsr166 1.8 try {
1328 jsr166 1.21 p.setKeepAliveTime(-1,MILLISECONDS);
1329 dl 1.1 shouldThrow();
1330 jsr166 1.4 } catch (IllegalArgumentException success) {
1331 dl 1.1 } finally {
1332 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1333 dl 1.1 }
1334 jsr166 1.21 joinPool(p);
1335 dl 1.1 }
1336    
1337     /**
1338     * terminated() is called on termination
1339     */
1340     public void testTerminated() {
1341 jsr166 1.21 CustomTPE p = new CustomTPE();
1342     try { p.shutdown(); } catch (SecurityException ok) { return; }
1343 jsr166 1.30 assertTrue(p.terminatedCalled());
1344 jsr166 1.21 joinPool(p);
1345 dl 1.1 }
1346    
1347     /**
1348     * beforeExecute and afterExecute are called when executing task
1349     */
1350 jsr166 1.5 public void testBeforeAfter() throws InterruptedException {
1351 jsr166 1.21 CustomTPE p = new CustomTPE();
1352 dl 1.1 try {
1353 jsr166 1.30 final CountDownLatch done = new CountDownLatch(1);
1354 jsr166 1.32 p.execute(new CheckedRunnable() {
1355 jsr166 1.30 public void realRun() {
1356     done.countDown();
1357 jsr166 1.32 }});
1358 jsr166 1.30 await(p.afterCalled);
1359     assertEquals(0, done.getCount());
1360     assertTrue(p.afterCalled());
1361     assertTrue(p.beforeCalled());
1362 jsr166 1.21 try { p.shutdown(); } catch (SecurityException ok) { return; }
1363 dl 1.1 } finally {
1364 jsr166 1.21 joinPool(p);
1365 dl 1.1 }
1366     }
1367    
1368     /**
1369     * completed submit of callable returns result
1370     */
1371 jsr166 1.5 public void testSubmitCallable() throws Exception {
1372 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1373 dl 1.1 try {
1374     Future<String> future = e.submit(new StringTask());
1375     String result = future.get();
1376     assertSame(TEST_STRING, result);
1377     } finally {
1378     joinPool(e);
1379     }
1380     }
1381    
1382     /**
1383     * completed submit of runnable returns successfully
1384     */
1385 jsr166 1.5 public void testSubmitRunnable() throws Exception {
1386 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1387 dl 1.1 try {
1388     Future<?> future = e.submit(new NoOpRunnable());
1389     future.get();
1390     assertTrue(future.isDone());
1391     } finally {
1392     joinPool(e);
1393     }
1394     }
1395    
1396     /**
1397     * completed submit of (runnable, result) returns result
1398     */
1399 jsr166 1.5 public void testSubmitRunnable2() throws Exception {
1400 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1401 dl 1.1 try {
1402     Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1403     String result = future.get();
1404     assertSame(TEST_STRING, result);
1405     } finally {
1406     joinPool(e);
1407     }
1408     }
1409    
1410     /**
1411     * invokeAny(null) throws NPE
1412     */
1413 jsr166 1.5 public void testInvokeAny1() throws Exception {
1414 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1415 dl 1.1 try {
1416     e.invokeAny(null);
1417 jsr166 1.5 shouldThrow();
1418 dl 1.1 } catch (NullPointerException success) {
1419     } finally {
1420     joinPool(e);
1421     }
1422     }
1423    
1424     /**
1425     * invokeAny(empty collection) throws IAE
1426     */
1427 jsr166 1.5 public void testInvokeAny2() throws Exception {
1428 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1429 dl 1.1 try {
1430     e.invokeAny(new ArrayList<Callable<String>>());
1431 jsr166 1.5 shouldThrow();
1432 dl 1.1 } catch (IllegalArgumentException success) {
1433     } finally {
1434     joinPool(e);
1435     }
1436     }
1437    
1438     /**
1439     * invokeAny(c) throws NPE if c has null elements
1440     */
1441 jsr166 1.5 public void testInvokeAny3() throws Exception {
1442 jsr166 1.17 CountDownLatch latch = new CountDownLatch(1);
1443 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1444 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1445     l.add(latchAwaitingStringTask(latch));
1446     l.add(null);
1447 dl 1.1 try {
1448     e.invokeAny(l);
1449 jsr166 1.5 shouldThrow();
1450 dl 1.1 } catch (NullPointerException success) {
1451     } finally {
1452 jsr166 1.5 latch.countDown();
1453 dl 1.1 joinPool(e);
1454     }
1455     }
1456    
1457     /**
1458     * invokeAny(c) throws ExecutionException if no task completes
1459     */
1460 jsr166 1.5 public void testInvokeAny4() throws Exception {
1461 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1462 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1463     l.add(new NPETask());
1464 dl 1.1 try {
1465     e.invokeAny(l);
1466 jsr166 1.5 shouldThrow();
1467 dl 1.1 } catch (ExecutionException success) {
1468 jsr166 1.13 assertTrue(success.getCause() instanceof NullPointerException);
1469 dl 1.1 } finally {
1470     joinPool(e);
1471     }
1472     }
1473    
1474     /**
1475     * invokeAny(c) returns result of some task
1476     */
1477 jsr166 1.5 public void testInvokeAny5() throws Exception {
1478 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1479 dl 1.1 try {
1480 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1481 dl 1.1 l.add(new StringTask());
1482     l.add(new StringTask());
1483     String result = e.invokeAny(l);
1484     assertSame(TEST_STRING, result);
1485     } finally {
1486     joinPool(e);
1487     }
1488     }
1489    
1490     /**
1491     * invokeAll(null) throws NPE
1492     */
1493 jsr166 1.5 public void testInvokeAll1() throws Exception {
1494 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1495 dl 1.1 try {
1496     e.invokeAll(null);
1497 jsr166 1.5 shouldThrow();
1498 dl 1.1 } catch (NullPointerException success) {
1499     } finally {
1500     joinPool(e);
1501     }
1502     }
1503    
1504     /**
1505     * invokeAll(empty collection) returns empty collection
1506     */
1507 jsr166 1.5 public void testInvokeAll2() throws Exception {
1508 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1509 dl 1.1 try {
1510     List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1511     assertTrue(r.isEmpty());
1512     } finally {
1513     joinPool(e);
1514     }
1515     }
1516    
1517     /**
1518     * invokeAll(c) throws NPE if c has null elements
1519     */
1520 jsr166 1.5 public void testInvokeAll3() throws Exception {
1521 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1522 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1523     l.add(new StringTask());
1524     l.add(null);
1525 dl 1.1 try {
1526     e.invokeAll(l);
1527 jsr166 1.5 shouldThrow();
1528 dl 1.1 } catch (NullPointerException success) {
1529     } finally {
1530     joinPool(e);
1531     }
1532     }
1533    
1534     /**
1535     * get of element of invokeAll(c) throws exception on failed task
1536     */
1537 jsr166 1.5 public void testInvokeAll4() throws Exception {
1538 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1539 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1540     l.add(new NPETask());
1541     List<Future<String>> futures = e.invokeAll(l);
1542     assertEquals(1, futures.size());
1543 dl 1.1 try {
1544 jsr166 1.17 futures.get(0).get();
1545 jsr166 1.5 shouldThrow();
1546 jsr166 1.3 } catch (ExecutionException success) {
1547 jsr166 1.15 assertTrue(success.getCause() instanceof NullPointerException);
1548 dl 1.1 } finally {
1549     joinPool(e);
1550     }
1551     }
1552    
1553     /**
1554     * invokeAll(c) returns results of all completed tasks
1555     */
1556 jsr166 1.5 public void testInvokeAll5() throws Exception {
1557 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1558 dl 1.1 try {
1559 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1560 dl 1.1 l.add(new StringTask());
1561     l.add(new StringTask());
1562 jsr166 1.17 List<Future<String>> futures = e.invokeAll(l);
1563     assertEquals(2, futures.size());
1564     for (Future<String> future : futures)
1565 jsr166 1.6 assertSame(TEST_STRING, future.get());
1566 dl 1.1 } finally {
1567     joinPool(e);
1568     }
1569     }
1570    
1571     /**
1572     * timed invokeAny(null) throws NPE
1573     */
1574 jsr166 1.5 public void testTimedInvokeAny1() throws Exception {
1575 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1576 dl 1.1 try {
1577 jsr166 1.9 e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1578 jsr166 1.5 shouldThrow();
1579 dl 1.1 } catch (NullPointerException success) {
1580     } finally {
1581     joinPool(e);
1582     }
1583     }
1584    
1585     /**
1586     * timed invokeAny(,,null) throws NPE
1587     */
1588 jsr166 1.5 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1589 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1590 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1591     l.add(new StringTask());
1592 dl 1.1 try {
1593     e.invokeAny(l, MEDIUM_DELAY_MS, null);
1594 jsr166 1.5 shouldThrow();
1595 dl 1.1 } catch (NullPointerException success) {
1596     } finally {
1597     joinPool(e);
1598     }
1599     }
1600    
1601     /**
1602     * timed invokeAny(empty collection) throws IAE
1603     */
1604 jsr166 1.5 public void testTimedInvokeAny2() throws Exception {
1605 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1606 dl 1.1 try {
1607 jsr166 1.9 e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1608 jsr166 1.5 shouldThrow();
1609 dl 1.1 } catch (IllegalArgumentException success) {
1610     } finally {
1611     joinPool(e);
1612     }
1613     }
1614    
1615     /**
1616     * timed invokeAny(c) throws NPE if c has null elements
1617     */
1618 jsr166 1.5 public void testTimedInvokeAny3() throws Exception {
1619 jsr166 1.17 CountDownLatch latch = new CountDownLatch(1);
1620 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1621 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1622     l.add(latchAwaitingStringTask(latch));
1623     l.add(null);
1624 dl 1.1 try {
1625 jsr166 1.9 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1626 jsr166 1.5 shouldThrow();
1627 dl 1.1 } catch (NullPointerException success) {
1628     } finally {
1629 jsr166 1.12 latch.countDown();
1630 dl 1.1 joinPool(e);
1631     }
1632     }
1633    
1634     /**
1635     * timed invokeAny(c) throws ExecutionException if no task completes
1636     */
1637 jsr166 1.5 public void testTimedInvokeAny4() throws Exception {
1638 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1639 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1640     l.add(new NPETask());
1641 dl 1.1 try {
1642 jsr166 1.9 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1643 jsr166 1.5 shouldThrow();
1644 jsr166 1.3 } catch (ExecutionException success) {
1645 jsr166 1.13 assertTrue(success.getCause() instanceof NullPointerException);
1646 dl 1.1 } finally {
1647     joinPool(e);
1648     }
1649     }
1650    
1651     /**
1652     * timed invokeAny(c) returns result of some task
1653     */
1654 jsr166 1.5 public void testTimedInvokeAny5() throws Exception {
1655 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1656 dl 1.1 try {
1657 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1658 dl 1.1 l.add(new StringTask());
1659     l.add(new StringTask());
1660 jsr166 1.9 String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1661 dl 1.1 assertSame(TEST_STRING, result);
1662     } finally {
1663     joinPool(e);
1664     }
1665     }
1666    
1667     /**
1668     * timed invokeAll(null) throws NPE
1669     */
1670 jsr166 1.5 public void testTimedInvokeAll1() throws Exception {
1671 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1672 dl 1.1 try {
1673 jsr166 1.9 e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1674 jsr166 1.5 shouldThrow();
1675 dl 1.1 } catch (NullPointerException success) {
1676     } finally {
1677     joinPool(e);
1678     }
1679     }
1680    
1681     /**
1682     * timed invokeAll(,,null) throws NPE
1683     */
1684 jsr166 1.5 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1685 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1686 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1687     l.add(new StringTask());
1688 dl 1.1 try {
1689     e.invokeAll(l, MEDIUM_DELAY_MS, null);
1690 jsr166 1.5 shouldThrow();
1691 dl 1.1 } catch (NullPointerException success) {
1692     } finally {
1693     joinPool(e);
1694     }
1695     }
1696    
1697     /**
1698     * timed invokeAll(empty collection) returns empty collection
1699     */
1700 jsr166 1.5 public void testTimedInvokeAll2() throws Exception {
1701 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1702 dl 1.1 try {
1703 jsr166 1.9 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1704 dl 1.1 assertTrue(r.isEmpty());
1705     } finally {
1706     joinPool(e);
1707     }
1708     }
1709    
1710     /**
1711     * timed invokeAll(c) throws NPE if c has null elements
1712     */
1713 jsr166 1.5 public void testTimedInvokeAll3() throws Exception {
1714 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1715 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1716     l.add(new StringTask());
1717     l.add(null);
1718 dl 1.1 try {
1719 jsr166 1.9 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1720 jsr166 1.5 shouldThrow();
1721 dl 1.1 } catch (NullPointerException success) {
1722     } finally {
1723     joinPool(e);
1724     }
1725     }
1726    
1727     /**
1728     * get of element of invokeAll(c) throws exception on failed task
1729     */
1730 jsr166 1.5 public void testTimedInvokeAll4() throws Exception {
1731 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1732 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1733     l.add(new NPETask());
1734     List<Future<String>> futures =
1735     e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1736     assertEquals(1, futures.size());
1737 dl 1.1 try {
1738 jsr166 1.17 futures.get(0).get();
1739 jsr166 1.5 shouldThrow();
1740 jsr166 1.3 } catch (ExecutionException success) {
1741 jsr166 1.6 assertTrue(success.getCause() instanceof NullPointerException);
1742 dl 1.1 } finally {
1743     joinPool(e);
1744     }
1745     }
1746    
1747     /**
1748     * timed invokeAll(c) returns results of all completed tasks
1749     */
1750 jsr166 1.5 public void testTimedInvokeAll5() throws Exception {
1751 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1752 dl 1.1 try {
1753 jsr166 1.17 List<Callable<String>> l = new ArrayList<Callable<String>>();
1754 dl 1.1 l.add(new StringTask());
1755     l.add(new StringTask());
1756 jsr166 1.17 List<Future<String>> futures =
1757 jsr166 1.45 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1758 jsr166 1.17 assertEquals(2, futures.size());
1759     for (Future<String> future : futures)
1760 jsr166 1.6 assertSame(TEST_STRING, future.get());
1761 dl 1.1 } finally {
1762     joinPool(e);
1763     }
1764     }
1765    
1766     /**
1767     * timed invokeAll(c) cancels tasks not completed by timeout
1768     */
1769 jsr166 1.5 public void testTimedInvokeAll6() throws Exception {
1770 jsr166 1.9 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1771 dl 1.1 try {
1772 jsr166 1.39 for (long timeout = timeoutMillis();;) {
1773     List<Callable<String>> tasks = new ArrayList<>();
1774     tasks.add(new StringTask("0"));
1775     tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1776     tasks.add(new StringTask("2"));
1777     long startTime = System.nanoTime();
1778     List<Future<String>> futures =
1779     e.invokeAll(tasks, timeout, MILLISECONDS);
1780     assertEquals(tasks.size(), futures.size());
1781     assertTrue(millisElapsedSince(startTime) >= timeout);
1782     for (Future future : futures)
1783     assertTrue(future.isDone());
1784     assertTrue(futures.get(1).isCancelled());
1785     try {
1786     assertEquals("0", futures.get(0).get());
1787     assertEquals("2", futures.get(2).get());
1788     break;
1789     } catch (CancellationException retryWithLongerTimeout) {
1790     timeout *= 2;
1791     if (timeout >= LONG_DELAY_MS / 2)
1792     fail("expected exactly one task to be cancelled");
1793     }
1794     }
1795 dl 1.1 } finally {
1796     joinPool(e);
1797     }
1798     }
1799    
1800     /**
1801     * Execution continues if there is at least one thread even if
1802     * thread factory fails to create more
1803     */
1804 jsr166 1.5 public void testFailingThreadFactory() throws InterruptedException {
1805 jsr166 1.21 final ExecutorService e =
1806     new CustomTPE(100, 100,
1807     LONG_DELAY_MS, MILLISECONDS,
1808     new LinkedBlockingQueue<Runnable>(),
1809     new FailingThreadFactory());
1810     try {
1811     final int TASKS = 100;
1812     final CountDownLatch done = new CountDownLatch(TASKS);
1813     for (int k = 0; k < TASKS; ++k)
1814     e.execute(new CheckedRunnable() {
1815     public void realRun() {
1816     done.countDown();
1817     }});
1818     assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1819 dl 1.1 } finally {
1820     joinPool(e);
1821     }
1822     }
1823    
1824     /**
1825     * allowsCoreThreadTimeOut is by default false.
1826     */
1827     public void testAllowsCoreThreadTimeOut() {
1828 jsr166 1.21 ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1829     assertFalse(p.allowsCoreThreadTimeOut());
1830     joinPool(p);
1831 dl 1.1 }
1832    
1833     /**
1834     * allowCoreThreadTimeOut(true) causes idle threads to time out
1835     */
1836 jsr166 1.21 public void testAllowCoreThreadTimeOut_true() throws Exception {
1837 jsr166 1.39 long keepAliveTime = timeoutMillis();
1838 jsr166 1.21 final ThreadPoolExecutor p =
1839     new CustomTPE(2, 10,
1840 jsr166 1.39 keepAliveTime, MILLISECONDS,
1841 jsr166 1.21 new ArrayBlockingQueue<Runnable>(10));
1842     final CountDownLatch threadStarted = new CountDownLatch(1);
1843     try {
1844     p.allowCoreThreadTimeOut(true);
1845     p.execute(new CheckedRunnable() {
1846 jsr166 1.39 public void realRun() {
1847 jsr166 1.21 threadStarted.countDown();
1848     assertEquals(1, p.getPoolSize());
1849     }});
1850 jsr166 1.29 await(threadStarted);
1851 jsr166 1.39 delay(keepAliveTime);
1852 jsr166 1.29 long startTime = System.nanoTime();
1853     while (p.getPoolSize() > 0
1854     && millisElapsedSince(startTime) < LONG_DELAY_MS)
1855     Thread.yield();
1856     assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1857 jsr166 1.21 assertEquals(0, p.getPoolSize());
1858 dl 1.1 } finally {
1859 jsr166 1.21 joinPool(p);
1860 dl 1.1 }
1861     }
1862    
1863     /**
1864     * allowCoreThreadTimeOut(false) causes idle threads not to time out
1865     */
1866 jsr166 1.21 public void testAllowCoreThreadTimeOut_false() throws Exception {
1867 jsr166 1.39 long keepAliveTime = timeoutMillis();
1868 jsr166 1.21 final ThreadPoolExecutor p =
1869     new CustomTPE(2, 10,
1870 jsr166 1.39 keepAliveTime, MILLISECONDS,
1871 jsr166 1.21 new ArrayBlockingQueue<Runnable>(10));
1872     final CountDownLatch threadStarted = new CountDownLatch(1);
1873     try {
1874     p.allowCoreThreadTimeOut(false);
1875     p.execute(new CheckedRunnable() {
1876     public void realRun() throws InterruptedException {
1877     threadStarted.countDown();
1878     assertTrue(p.getPoolSize() >= 1);
1879     }});
1880 jsr166 1.39 delay(2 * keepAliveTime);
1881 jsr166 1.21 assertTrue(p.getPoolSize() >= 1);
1882 dl 1.1 } finally {
1883 jsr166 1.21 joinPool(p);
1884 dl 1.1 }
1885     }
1886    
1887 jsr166 1.44 /**
1888     * get(cancelled task) throws CancellationException
1889     * (in part, a test of CustomTPE itself)
1890     */
1891     public void testGet_cancelled() throws Exception {
1892     final ExecutorService e =
1893     new CustomTPE(1, 1,
1894     LONG_DELAY_MS, MILLISECONDS,
1895     new LinkedBlockingQueue<Runnable>());
1896     try {
1897     final CountDownLatch blockerStarted = new CountDownLatch(1);
1898     final CountDownLatch done = new CountDownLatch(1);
1899     final List<Future<?>> futures = new ArrayList<>();
1900     for (int i = 0; i < 2; i++) {
1901     Runnable r = new CheckedRunnable() { public void realRun()
1902     throws Throwable {
1903     blockerStarted.countDown();
1904     assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
1905     }};
1906     futures.add(e.submit(r));
1907     }
1908     assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
1909     for (Future<?> future : futures) future.cancel(false);
1910     for (Future<?> future : futures) {
1911     try {
1912     future.get();
1913     shouldThrow();
1914     } catch (CancellationException success) {}
1915     try {
1916     future.get(LONG_DELAY_MS, MILLISECONDS);
1917     shouldThrow();
1918     } catch (CancellationException success) {}
1919     assertTrue(future.isCancelled());
1920     assertTrue(future.isDone());
1921     }
1922     done.countDown();
1923     } finally {
1924     joinPool(e);
1925     }
1926     }
1927    
1928 dl 1.1 }