ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorsTest.java
Revision: 1.8
Committed: Sat Nov 1 18:37:02 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_NOV3_FREEZE
Changes since 1.7: +169 -0 lines
Log Message:
Revised and added tests for revised PFT

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by members of JCP JSR-166 Expert Group and released to the
3     * public domain. Use, modify, and redistribute this code in any way
4     * without acknowledgement. Other contributors include Andrew Wright,
5     * Jeffrey Hayes, Pat Fischer, Mike Judd.
6     */
7    
8    
9     import junit.framework.*;
10     import java.util.*;
11     import java.util.concurrent.*;
12 dl 1.2 import java.math.BigInteger;
13 dl 1.8 import java.security.*;
14 dl 1.1
15 dl 1.3 public class ExecutorsTest extends JSR166TestCase{
16 dl 1.1 public static void main(String[] args) {
17     junit.textui.TestRunner.run (suite());
18     }
19     public static Test suite() {
20     return new TestSuite(ExecutorsTest.class);
21     }
22    
23 dl 1.4 private static final String TEST_STRING = "a test string";
24    
25     private static class StringTask implements Callable<String> {
26     public String call() { return TEST_STRING; }
27     }
28    
29     static class DirectExecutor implements Executor {
30     public void execute(Runnable r) {
31     r.run();
32     }
33     }
34    
35     static class TimedCallable<T> implements Callable<T> {
36     private final Executor exec;
37     private final Callable<T> func;
38     private final long msecs;
39    
40     TimedCallable(Executor exec, Callable<T> func, long msecs) {
41     this.exec = exec;
42     this.func = func;
43     this.msecs = msecs;
44     }
45    
46     public T call() throws Exception {
47     Future<T> ftask = Executors.execute(exec, func);
48     try {
49     return ftask.get(msecs, TimeUnit.MILLISECONDS);
50     } finally {
51     ftask.cancel(true);
52     }
53     }
54     }
55    
56    
57     private static class Fib implements Callable<BigInteger> {
58     private final BigInteger n;
59     Fib(long n) {
60     if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
61     this.n = BigInteger.valueOf(n);
62     }
63     public BigInteger call() {
64     BigInteger f1 = BigInteger.ONE;
65     BigInteger f2 = f1;
66     for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
67     BigInteger t = f1.add(f2);
68     f1 = f2;
69     f2 = t;
70     }
71     return f1;
72     }
73     };
74    
75 dl 1.5 /**
76     * A newCachedThreadPool can execute runnables
77     */
78     public void testNewCachedThreadPool1() {
79     ExecutorService e = Executors.newCachedThreadPool();
80     e.execute(new NoOpRunnable());
81     e.execute(new NoOpRunnable());
82     e.execute(new NoOpRunnable());
83     e.shutdown();
84     }
85    
86     /**
87     * A newCachedThreadPool with given ThreadFactory can execute runnables
88     */
89     public void testNewCachedThreadPool2() {
90 dl 1.6 ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
91 dl 1.5 e.execute(new NoOpRunnable());
92     e.execute(new NoOpRunnable());
93     e.execute(new NoOpRunnable());
94     e.shutdown();
95     }
96    
97     /**
98     * A newCachedThreadPool with null ThreadFactory throws NPE
99     */
100     public void testNewCachedThreadPool3() {
101     try {
102     ExecutorService e = Executors.newCachedThreadPool(null);
103     shouldThrow();
104     }
105     catch(NullPointerException success) {
106     }
107     }
108    
109    
110     /**
111     * A new SingleThreadExecutor can execute runnables
112     */
113     public void testNewSingleThreadExecutor1() {
114     ExecutorService e = Executors.newSingleThreadExecutor();
115     e.execute(new NoOpRunnable());
116     e.execute(new NoOpRunnable());
117     e.execute(new NoOpRunnable());
118     e.shutdown();
119     }
120    
121     /**
122     * A new SingleThreadExecutor with given ThreadFactory can execute runnables
123     */
124     public void testNewSingleThreadExecutor2() {
125 dl 1.6 ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
126 dl 1.5 e.execute(new NoOpRunnable());
127     e.execute(new NoOpRunnable());
128     e.execute(new NoOpRunnable());
129     e.shutdown();
130     }
131    
132     /**
133     * A new SingleThreadExecutor with null ThreadFactory throws NPE
134     */
135     public void testNewSingleThreadExecutor3() {
136     try {
137     ExecutorService e = Executors.newSingleThreadExecutor(null);
138     shouldThrow();
139     }
140     catch(NullPointerException success) {
141     }
142     }
143    
144     /**
145     * A new newFixedThreadPool can execute runnables
146     */
147     public void testNewFixedThreadPool1() {
148     ExecutorService e = Executors.newFixedThreadPool(2);
149     e.execute(new NoOpRunnable());
150     e.execute(new NoOpRunnable());
151     e.execute(new NoOpRunnable());
152     e.shutdown();
153     }
154    
155     /**
156     * A new newFixedThreadPool with given ThreadFactory can execute runnables
157     */
158     public void testNewFixedThreadPool2() {
159 dl 1.6 ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
160 dl 1.5 e.execute(new NoOpRunnable());
161     e.execute(new NoOpRunnable());
162     e.execute(new NoOpRunnable());
163     e.shutdown();
164     }
165    
166     /**
167     * A new newFixedThreadPool with null ThreadFactory throws NPE
168     */
169     public void testNewFixedThreadPool3() {
170     try {
171     ExecutorService e = Executors.newFixedThreadPool(2, null);
172     shouldThrow();
173     }
174     catch(NullPointerException success) {
175     }
176     }
177    
178     /**
179     * A new newFixedThreadPool with 0 threads throws IAE
180     */
181     public void testNewFixedThreadPool4() {
182     try {
183     ExecutorService e = Executors.newFixedThreadPool(0);
184     shouldThrow();
185     }
186     catch(IllegalArgumentException success) {
187     }
188     }
189    
190     /**
191     * execute of runnable runs it to completion
192     */
193 dl 1.7 public void testExecuteRunnable() {
194 dl 1.5 try {
195     Executor e = new DirectExecutor();
196 dl 1.7 TrackedShortRunnable task = new TrackedShortRunnable();
197 dl 1.6 assertFalse(task.done);
198 dl 1.5 Future<String> future = Executors.execute(e, task, TEST_STRING);
199     String result = future.get();
200 dl 1.6 assertTrue(task.done);
201 dl 1.5 assertSame(TEST_STRING, result);
202     }
203     catch (ExecutionException ex) {
204     unexpectedException();
205     }
206     catch (InterruptedException ex) {
207     unexpectedException();
208     }
209     }
210    
211     /**
212     * invoke of a runnable runs it to completion
213     */
214 dl 1.7 public void testInvokeRunnable() {
215 dl 1.5 try {
216     Executor e = new DirectExecutor();
217 dl 1.7 TrackedShortRunnable task = new TrackedShortRunnable();
218 dl 1.6 assertFalse(task.done);
219 dl 1.5 Executors.invoke(e, task);
220 dl 1.6 assertTrue(task.done);
221 dl 1.5 }
222     catch (ExecutionException ex) {
223     unexpectedException();
224     }
225     catch (InterruptedException ex) {
226     unexpectedException();
227     }
228     }
229    
230     /**
231     * execute of a callable runs it to completion
232     */
233 dl 1.7 public void testExecuteCallable() {
234 dl 1.5 try {
235     Executor e = new DirectExecutor();
236     Future<String> future = Executors.execute(e, new StringTask());
237     String result = future.get();
238     assertSame(TEST_STRING, result);
239     }
240     catch (ExecutionException ex) {
241     unexpectedException();
242     }
243     catch (InterruptedException ex) {
244     unexpectedException();
245     }
246     }
247    
248 dl 1.8
249     /**
250     * execute of a privileged action runs it to completion
251     */
252     public void testExecutePrivilegedAction() {
253     Policy savedPolicy = Policy.getPolicy();
254     AdjustablePolicy policy = new AdjustablePolicy();
255     policy.addPermission(new RuntimePermission("getContextClassLoader"));
256     policy.addPermission(new RuntimePermission("setContextClassLoader"));
257     Policy.setPolicy(policy);
258     try {
259     Executor e = new DirectExecutor();
260     Future future = Executors.execute(e, new PrivilegedAction() {
261     public Object run() {
262     return TEST_STRING;
263     }});
264    
265     Object result = future.get();
266     assertSame(TEST_STRING, result);
267     }
268     catch (ExecutionException ex) {
269     unexpectedException();
270     }
271     catch (InterruptedException ex) {
272     unexpectedException();
273     }
274     finally {
275     Policy.setPolicy(savedPolicy);
276     }
277     }
278    
279     /**
280     * execute of a privileged exception action runs it to completion
281     */
282     public void testExecutePrivilegedExceptionAction() {
283     Policy savedPolicy = Policy.getPolicy();
284     AdjustablePolicy policy = new AdjustablePolicy();
285     policy.addPermission(new RuntimePermission("getContextClassLoader"));
286     policy.addPermission(new RuntimePermission("setContextClassLoader"));
287     Policy.setPolicy(policy);
288     try {
289     Executor e = new DirectExecutor();
290     Future future = Executors.execute(e, new PrivilegedExceptionAction() {
291     public Object run() {
292     return TEST_STRING;
293     }});
294    
295     Object result = future.get();
296     assertSame(TEST_STRING, result);
297     }
298     catch (ExecutionException ex) {
299     unexpectedException();
300     }
301     catch (InterruptedException ex) {
302     unexpectedException();
303     }
304     finally {
305     Policy.setPolicy(savedPolicy);
306     }
307     }
308    
309     /**
310     * execute of a failed privileged exception action reports exception
311     */
312     public void testExecuteFailedPrivilegedExceptionAction() {
313     Policy savedPolicy = Policy.getPolicy();
314     AdjustablePolicy policy = new AdjustablePolicy();
315     policy.addPermission(new RuntimePermission("getContextClassLoader"));
316     policy.addPermission(new RuntimePermission("setContextClassLoader"));
317     Policy.setPolicy(policy);
318     try {
319     Executor e = new DirectExecutor();
320     Future future = Executors.execute(e, new PrivilegedExceptionAction() {
321     public Object run() throws Exception {
322     throw new IndexOutOfBoundsException();
323     }});
324    
325     Object result = future.get();
326     shouldThrow();
327     }
328     catch (ExecutionException success) {
329     }
330     catch (InterruptedException ex) {
331     unexpectedException();
332     }
333     finally {
334     Policy.setPolicy(savedPolicy);
335     }
336     }
337    
338 dl 1.5 /**
339     * invoke of a collable runs it to completion
340     */
341 dl 1.7 public void testInvokeCallable() {
342 dl 1.5 try {
343     Executor e = new DirectExecutor();
344     String result = Executors.invoke(e, new StringTask());
345    
346     assertSame(TEST_STRING, result);
347     }
348     catch (ExecutionException ex) {
349     unexpectedException();
350     }
351     catch (InterruptedException ex) {
352     unexpectedException();
353     }
354     }
355 dl 1.4
356 dl 1.5 /**
357     * execute with null executor throws NPE
358     */
359 dl 1.7 public void testNullExecuteRunnable() {
360 dl 1.5 try {
361 dl 1.7 TrackedShortRunnable task = new TrackedShortRunnable();
362 dl 1.6 assertFalse(task.done);
363 dl 1.5 Future<String> future = Executors.execute(null, task, TEST_STRING);
364     shouldThrow();
365     }
366     catch (NullPointerException success) {
367     }
368     catch (Exception ex) {
369     unexpectedException();
370     }
371     }
372 dl 1.4
373 dl 1.1 /**
374 dl 1.5 * execute with a null runnable throws NPE
375     */
376     public void testExecuteNullRunnable() {
377     try {
378     Executor e = new DirectExecutor();
379 dl 1.7 TrackedShortRunnable task = null;
380 dl 1.5 Future<String> future = Executors.execute(e, task, TEST_STRING);
381     shouldThrow();
382     }
383     catch (NullPointerException success) {
384     }
385     catch (Exception ex) {
386     unexpectedException();
387     }
388     }
389    
390     /**
391     * invoke of a null runnable throws NPE
392     */
393 dl 1.7 public void testInvokeNullRunnable() {
394 dl 1.5 try {
395     Executor e = new DirectExecutor();
396 dl 1.7 TrackedShortRunnable task = null;
397 dl 1.5 Executors.invoke(e, task);
398     shouldThrow();
399     }
400     catch (NullPointerException success) {
401     }
402     catch (Exception ex) {
403     unexpectedException();
404     }
405     }
406    
407     /**
408     * execute of a null callable throws NPE
409     */
410 dl 1.7 public void testExecuteNullCallable() {
411 dl 1.5 try {
412     Executor e = new DirectExecutor();
413     StringTask t = null;
414     Future<String> future = Executors.execute(e, t);
415     shouldThrow();
416     }
417     catch (NullPointerException success) {
418     }
419     catch (Exception ex) {
420     unexpectedException();
421     }
422     }
423    
424     /**
425     * invoke of a null callable throws NPE
426     */
427 dl 1.7 public void testInvokeNullCallable() {
428 dl 1.5 try {
429     Executor e = new DirectExecutor();
430     StringTask t = null;
431     String result = Executors.invoke(e, t);
432     shouldThrow();
433     }
434     catch (NullPointerException success) {
435     }
436     catch (Exception ex) {
437     unexpectedException();
438     }
439     }
440    
441     /**
442     * execute(Executor, Runnable) throws RejectedExecutionException
443     * if saturated.
444 dl 1.1 */
445 dl 1.4 public void testExecute1() {
446 dl 1.3 ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
447 dl 1.4 try {
448 dl 1.1
449     for(int i = 0; i < 5; ++i){
450 dl 1.3 Executors.execute(p, new MediumRunnable(), Boolean.TRUE);
451 dl 1.1 }
452 dl 1.4 shouldThrow();
453 dl 1.1 } catch(RejectedExecutionException success){}
454 dl 1.3 joinPool(p);
455 dl 1.1 }
456    
457     /**
458 dl 1.5 * execute(Executor, Callable)throws RejectedExecutionException
459     * if saturated.
460 dl 1.1 */
461 dl 1.4 public void testExecute2() {
462 dl 1.3 ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
463 dl 1.4 try {
464 dl 1.1 for(int i = 0; i < 5; ++i) {
465 dl 1.3 Executors.execute(p, new SmallCallable());
466 dl 1.1 }
467 dl 1.4 shouldThrow();
468     } catch(RejectedExecutionException e){}
469 dl 1.3 joinPool(p);
470 dl 1.1 }
471    
472    
473     /**
474 dl 1.5 * invoke(Executor, Runnable) throws InterruptedException if
475     * caller interrupted.
476 dl 1.1 */
477 dl 1.5 public void testInterruptedInvoke() {
478 dl 1.3 final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
479 dl 1.1 Thread t = new Thread(new Runnable() {
480 dl 1.4 public void run() {
481     try {
482     Executors.invoke(p,new Runnable() {
483     public void run() {
484     try {
485 dl 1.1 Thread.sleep(MEDIUM_DELAY_MS);
486 dl 1.4 shouldThrow();
487     } catch(InterruptedException e){
488 dl 1.1 }
489     }
490     });
491     } catch(InterruptedException success){
492     } catch(Exception e) {
493 dl 1.4 unexpectedException();
494 dl 1.1 }
495    
496     }
497     });
498 dl 1.4 try {
499 dl 1.1 t.start();
500     Thread.sleep(SHORT_DELAY_MS);
501     t.interrupt();
502 dl 1.4 } catch(Exception e){
503     unexpectedException();
504 dl 1.1 }
505 dl 1.3 joinPool(p);
506 dl 1.1 }
507    
508     /**
509 dl 1.5 * invoke(Executor, Runnable) throws ExecutionException if
510     * runnable throws exception.
511 dl 1.1 */
512 dl 1.4 public void testInvoke3() {
513 dl 1.3 ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
514 dl 1.4 try {
515     Runnable r = new Runnable() {
516     public void run() {
517 dl 1.1 int i = 5/0;
518     }
519     };
520    
521     for(int i =0; i < 5; i++){
522     Executors.invoke(p,r);
523     }
524    
525 dl 1.4 shouldThrow();
526 dl 1.1 } catch(ExecutionException success){
527     } catch(Exception e){
528 dl 1.4 unexpectedException();
529 dl 1.1 }
530 dl 1.3 joinPool(p);
531 dl 1.1 }
532    
533    
534    
535     /**
536 dl 1.5 * invoke(Executor, Callable) throws InterruptedException if
537     * callable throws exception
538 dl 1.1 */
539 dl 1.4 public void testInvoke5() {
540 dl 1.3 final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
541 dl 1.1
542 dl 1.4 final Callable c = new Callable() {
543     public Object call() {
544     try {
545 dl 1.3 Executors.invoke(p, new SmallCallable());
546 dl 1.4 shouldThrow();
547     } catch(InterruptedException e){}
548 dl 1.1 catch(RejectedExecutionException e2){}
549     catch(ExecutionException e3){}
550     return Boolean.TRUE;
551     }
552     };
553    
554    
555    
556 dl 1.4 Thread t = new Thread(new Runnable() {
557     public void run() {
558     try {
559 dl 1.1 c.call();
560 dl 1.4 } catch(Exception e){}
561 dl 1.1 }
562     });
563 dl 1.4 try {
564 dl 1.1 t.start();
565     Thread.sleep(SHORT_DELAY_MS);
566     t.interrupt();
567     t.join();
568 dl 1.4 } catch(InterruptedException e){
569     unexpectedException();
570 dl 1.1 }
571    
572 dl 1.3 joinPool(p);
573 dl 1.1 }
574    
575     /**
576 dl 1.5 * invoke(Executor, Callable) will throw ExecutionException
577     * if callable throws exception
578 dl 1.1 */
579 dl 1.4 public void testInvoke6() {
580 dl 1.3 ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
581 dl 1.1
582 dl 1.4 try {
583     Callable c = new Callable() {
584     public Object call() {
585 dl 1.1 int i = 5/0;
586     return Boolean.TRUE;
587     }
588     };
589    
590     for(int i =0; i < 5; i++){
591     Executors.invoke(p,c);
592     }
593    
594 dl 1.4 shouldThrow();
595 dl 1.5 }
596     catch(ExecutionException success){
597     } catch(Exception e) {
598 dl 1.4 unexpectedException();
599 dl 1.1 }
600 dl 1.5 joinPool(p);
601 dl 1.1 }
602    
603    
604 dl 1.2
605     /**
606 dl 1.4 * timeouts from execute will time out if they compute too long.
607 dl 1.2 */
608     public void testTimedCallable() {
609     int N = 10000;
610     ExecutorService executor = Executors.newSingleThreadExecutor();
611     List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
612     try {
613     long startTime = System.currentTimeMillis();
614    
615     long i = 0;
616     while (tasks.size() < N) {
617     tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
618     i += 10;
619     }
620    
621     int iters = 0;
622     BigInteger sum = BigInteger.ZERO;
623     for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
624     try {
625     ++iters;
626     sum = sum.add(it.next().call());
627     }
628     catch (TimeoutException success) {
629     assertTrue(iters > 0);
630     return;
631     }
632     catch (Exception e) {
633 dl 1.4 unexpectedException();
634 dl 1.2 }
635     }
636     // if by chance we didn't ever time out, total time must be small
637     long elapsed = System.currentTimeMillis() - startTime;
638     assertTrue(elapsed < N);
639     }
640     finally {
641 dl 1.3 joinPool(executor);
642 dl 1.2 }
643     }
644    
645    
646 dl 1.8 /**
647     * ThreadPoolExecutor using defaultThreadFactory has
648     * specified group, priority, daemon status, and name
649     */
650     public void testDefaultThreadFactory() {
651     final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
652     Runnable r = new Runnable() {
653     public void run() {
654     Thread current = Thread.currentThread();
655     threadAssertTrue(!current.isDaemon());
656     threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
657     ThreadGroup g = current.getThreadGroup();
658     SecurityManager s = System.getSecurityManager();
659     if (s != null)
660     threadAssertTrue(g == s.getThreadGroup());
661     else
662     threadAssertTrue(g == egroup);
663     String name = current.getName();
664     threadAssertTrue(name.endsWith("thread-1"));
665     }
666     };
667     ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
668    
669     e.execute(r);
670     e.shutdown();
671     try {
672     Thread.sleep(SHORT_DELAY_MS);
673     } catch (Exception eX) {
674     unexpectedException();
675     } finally {
676     joinPool(e);
677     }
678     }
679    
680     /**
681     * ThreadPoolExecutor using privilegedThreadFactory has
682     * specified group, priority, daemon status, name,
683     * access control context and context class loader
684     */
685     public void testPrivilegedThreadFactory() {
686     Policy savedPolicy = Policy.getPolicy();
687     AdjustablePolicy policy = new AdjustablePolicy();
688     policy.addPermission(new RuntimePermission("getContextClassLoader"));
689     policy.addPermission(new RuntimePermission("setContextClassLoader"));
690     Policy.setPolicy(policy);
691     final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
692     final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
693     final AccessControlContext thisacc = AccessController.getContext();
694     Runnable r = new Runnable() {
695     public void run() {
696     Thread current = Thread.currentThread();
697     threadAssertTrue(!current.isDaemon());
698     threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
699     ThreadGroup g = current.getThreadGroup();
700     SecurityManager s = System.getSecurityManager();
701     if (s != null)
702     threadAssertTrue(g == s.getThreadGroup());
703     else
704     threadAssertTrue(g == egroup);
705     String name = current.getName();
706     threadAssertTrue(name.endsWith("thread-1"));
707     threadAssertTrue(thisccl == current.getContextClassLoader());
708     threadAssertTrue(thisacc.equals(AccessController.getContext()));
709     }
710     };
711     ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
712    
713     Policy.setPolicy(savedPolicy);
714     e.execute(r);
715     e.shutdown();
716     try {
717     Thread.sleep(SHORT_DELAY_MS);
718     } catch (Exception ex) {
719     unexpectedException();
720     } finally {
721     joinPool(e);
722     }
723 dl 1.1
724 dl 1.8 }
725 dl 1.1
726     }