ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorsTest.java
Revision: 1.18
Committed: Tue Aug 4 13:58:09 2009 UTC (14 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.17: +6 -1 lines
Log Message:
Track 1.6 change to use security manager, not AccessControl

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.12 * 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     * http://creativecommons.org/licenses/publicdomain
5     * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9    
10     import junit.framework.*;
11     import java.util.*;
12     import java.util.concurrent.*;
13 dl 1.2 import java.math.BigInteger;
14 dl 1.8 import java.security.*;
15 dl 1.18 import sun.security.util.SecurityConstants;
16 dl 1.1
17 dl 1.3 public class ExecutorsTest extends JSR166TestCase{
18 dl 1.1 public static void main(String[] args) {
19 tim 1.9 junit.textui.TestRunner.run (suite());
20 dl 1.1 }
21     public static Test suite() {
22 tim 1.9 return new TestSuite(ExecutorsTest.class);
23 dl 1.1 }
24    
25 dl 1.4 static class TimedCallable<T> implements Callable<T> {
26 tim 1.10 private final ExecutorService exec;
27 dl 1.4 private final Callable<T> func;
28     private final long msecs;
29    
30 tim 1.10 TimedCallable(ExecutorService exec, Callable<T> func, long msecs) {
31 dl 1.4 this.exec = exec;
32     this.func = func;
33     this.msecs = msecs;
34     }
35    
36     public T call() throws Exception {
37 tim 1.10 Future<T> ftask = exec.submit(func);
38 dl 1.4 try {
39     return ftask.get(msecs, TimeUnit.MILLISECONDS);
40     } finally {
41     ftask.cancel(true);
42     }
43     }
44     }
45    
46    
47     private static class Fib implements Callable<BigInteger> {
48     private final BigInteger n;
49     Fib(long n) {
50     if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
51     this.n = BigInteger.valueOf(n);
52     }
53     public BigInteger call() {
54     BigInteger f1 = BigInteger.ONE;
55     BigInteger f2 = f1;
56     for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
57     BigInteger t = f1.add(f2);
58     f1 = f2;
59     f2 = t;
60     }
61     return f1;
62     }
63     };
64    
65 dl 1.5 /**
66     * A newCachedThreadPool can execute runnables
67     */
68     public void testNewCachedThreadPool1() {
69     ExecutorService e = Executors.newCachedThreadPool();
70     e.execute(new NoOpRunnable());
71     e.execute(new NoOpRunnable());
72     e.execute(new NoOpRunnable());
73 dl 1.14 joinPool(e);
74 dl 1.5 }
75    
76     /**
77     * A newCachedThreadPool with given ThreadFactory can execute runnables
78     */
79     public void testNewCachedThreadPool2() {
80 dl 1.6 ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
81 dl 1.5 e.execute(new NoOpRunnable());
82     e.execute(new NoOpRunnable());
83     e.execute(new NoOpRunnable());
84 dl 1.14 joinPool(e);
85 dl 1.5 }
86    
87     /**
88     * A newCachedThreadPool with null ThreadFactory throws NPE
89     */
90     public void testNewCachedThreadPool3() {
91     try {
92     ExecutorService e = Executors.newCachedThreadPool(null);
93     shouldThrow();
94     }
95     catch(NullPointerException success) {
96     }
97     }
98    
99    
100     /**
101     * A new SingleThreadExecutor can execute runnables
102     */
103     public void testNewSingleThreadExecutor1() {
104     ExecutorService e = Executors.newSingleThreadExecutor();
105     e.execute(new NoOpRunnable());
106     e.execute(new NoOpRunnable());
107     e.execute(new NoOpRunnable());
108 dl 1.14 joinPool(e);
109 dl 1.5 }
110    
111     /**
112     * A new SingleThreadExecutor with given ThreadFactory can execute runnables
113     */
114     public void testNewSingleThreadExecutor2() {
115 dl 1.6 ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
116 dl 1.5 e.execute(new NoOpRunnable());
117     e.execute(new NoOpRunnable());
118     e.execute(new NoOpRunnable());
119 dl 1.14 joinPool(e);
120 dl 1.5 }
121    
122     /**
123     * A new SingleThreadExecutor with null ThreadFactory throws NPE
124     */
125     public void testNewSingleThreadExecutor3() {
126     try {
127     ExecutorService e = Executors.newSingleThreadExecutor(null);
128     shouldThrow();
129     }
130     catch(NullPointerException success) {
131     }
132     }
133    
134     /**
135 dl 1.11 * A new SingleThreadExecutor cannot be casted to concrete implementation
136     */
137     public void testCastNewSingleThreadExecutor() {
138     ExecutorService e = Executors.newSingleThreadExecutor();
139     try {
140     ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
141     } catch (ClassCastException success) {
142     } finally {
143     joinPool(e);
144     }
145     }
146    
147    
148     /**
149 dl 1.5 * A new newFixedThreadPool can execute runnables
150     */
151     public void testNewFixedThreadPool1() {
152     ExecutorService e = Executors.newFixedThreadPool(2);
153     e.execute(new NoOpRunnable());
154     e.execute(new NoOpRunnable());
155     e.execute(new NoOpRunnable());
156 dl 1.14 joinPool(e);
157 dl 1.5 }
158    
159     /**
160     * A new newFixedThreadPool with given ThreadFactory can execute runnables
161     */
162     public void testNewFixedThreadPool2() {
163 dl 1.6 ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
164 dl 1.5 e.execute(new NoOpRunnable());
165     e.execute(new NoOpRunnable());
166     e.execute(new NoOpRunnable());
167 dl 1.14 joinPool(e);
168 dl 1.5 }
169    
170     /**
171     * A new newFixedThreadPool with null ThreadFactory throws NPE
172     */
173     public void testNewFixedThreadPool3() {
174     try {
175     ExecutorService e = Executors.newFixedThreadPool(2, null);
176     shouldThrow();
177     }
178     catch(NullPointerException success) {
179     }
180     }
181    
182     /**
183     * A new newFixedThreadPool with 0 threads throws IAE
184     */
185     public void testNewFixedThreadPool4() {
186     try {
187     ExecutorService e = Executors.newFixedThreadPool(0);
188     shouldThrow();
189     }
190     catch(IllegalArgumentException success) {
191     }
192     }
193 dl 1.1
194 dl 1.2
195     /**
196 dl 1.11 * An unconfigurable newFixedThreadPool can execute runnables
197     */
198     public void testunconfigurableExecutorService() {
199     ExecutorService e = Executors.unconfigurableExecutorService(Executors.newFixedThreadPool(2));
200     e.execute(new NoOpRunnable());
201     e.execute(new NoOpRunnable());
202     e.execute(new NoOpRunnable());
203 dl 1.14 joinPool(e);
204 dl 1.11 }
205    
206     /**
207     * unconfigurableExecutorService(null) throws NPE
208     */
209     public void testunconfigurableExecutorServiceNPE() {
210     try {
211     ExecutorService e = Executors.unconfigurableExecutorService(null);
212     }
213     catch (NullPointerException success) {
214     }
215     }
216    
217     /**
218     * unconfigurableScheduledExecutorService(null) throws NPE
219     */
220     public void testunconfigurableScheduledExecutorServiceNPE() {
221     try {
222     ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
223     }
224     catch (NullPointerException success) {
225     }
226     }
227    
228    
229     /**
230     * a newSingleThreadScheduledExecutor successfully runs delayed task
231     */
232     public void testNewSingleThreadScheduledExecutor() {
233     try {
234     TrackedCallable callable = new TrackedCallable();
235     ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
236     Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
237     assertFalse(callable.done);
238     Thread.sleep(MEDIUM_DELAY_MS);
239     assertTrue(callable.done);
240     assertEquals(Boolean.TRUE, f.get());
241     joinPool(p1);
242     } catch(RejectedExecutionException e){}
243     catch(Exception e){
244     e.printStackTrace();
245     unexpectedException();
246     }
247     }
248    
249     /**
250     * a newScheduledThreadPool successfully runs delayed task
251     */
252     public void testnewScheduledThreadPool() {
253     try {
254     TrackedCallable callable = new TrackedCallable();
255     ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
256     Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
257     assertFalse(callable.done);
258     Thread.sleep(MEDIUM_DELAY_MS);
259     assertTrue(callable.done);
260     assertEquals(Boolean.TRUE, f.get());
261     joinPool(p1);
262     } catch(RejectedExecutionException e){}
263     catch(Exception e){
264     e.printStackTrace();
265     unexpectedException();
266     }
267     }
268    
269     /**
270     * an unconfigurable newScheduledThreadPool successfully runs delayed task
271     */
272     public void testunconfigurableScheduledExecutorService() {
273     try {
274     TrackedCallable callable = new TrackedCallable();
275     ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
276     Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
277     assertFalse(callable.done);
278     Thread.sleep(MEDIUM_DELAY_MS);
279     assertTrue(callable.done);
280     assertEquals(Boolean.TRUE, f.get());
281     joinPool(p1);
282     } catch(RejectedExecutionException e){}
283     catch(Exception e){
284     e.printStackTrace();
285     unexpectedException();
286     }
287     }
288    
289     /**
290 dl 1.4 * timeouts from execute will time out if they compute too long.
291 dl 1.2 */
292     public void testTimedCallable() {
293     int N = 10000;
294     ExecutorService executor = Executors.newSingleThreadExecutor();
295     List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
296     try {
297     long startTime = System.currentTimeMillis();
298    
299     long i = 0;
300     while (tasks.size() < N) {
301     tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
302     i += 10;
303     }
304    
305     int iters = 0;
306     BigInteger sum = BigInteger.ZERO;
307     for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
308     try {
309     ++iters;
310     sum = sum.add(it.next().call());
311     }
312     catch (TimeoutException success) {
313     assertTrue(iters > 0);
314     return;
315     }
316     catch (Exception e) {
317 dl 1.4 unexpectedException();
318 dl 1.2 }
319     }
320     // if by chance we didn't ever time out, total time must be small
321     long elapsed = System.currentTimeMillis() - startTime;
322     assertTrue(elapsed < N);
323     }
324     finally {
325 dl 1.3 joinPool(executor);
326 dl 1.2 }
327     }
328    
329    
330 dl 1.8 /**
331     * ThreadPoolExecutor using defaultThreadFactory has
332     * specified group, priority, daemon status, and name
333     */
334     public void testDefaultThreadFactory() {
335 tim 1.9 final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
336     Runnable r = new Runnable() {
337     public void run() {
338 dl 1.13 try {
339     Thread current = Thread.currentThread();
340     threadAssertTrue(!current.isDaemon());
341 dl 1.17 threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
342 dl 1.13 ThreadGroup g = current.getThreadGroup();
343     SecurityManager s = System.getSecurityManager();
344     if (s != null)
345     threadAssertTrue(g == s.getThreadGroup());
346     else
347     threadAssertTrue(g == egroup);
348     String name = current.getName();
349     threadAssertTrue(name.endsWith("thread-1"));
350     } catch (SecurityException ok) {
351     // Also pass if not allowed to change setting
352     }
353 tim 1.9 }
354     };
355     ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
356    
357     e.execute(r);
358 dl 1.14 try {
359     e.shutdown();
360     } catch(SecurityException ok) {
361     }
362    
363 tim 1.9 try {
364     Thread.sleep(SHORT_DELAY_MS);
365     } catch (Exception eX) {
366     unexpectedException();
367     } finally {
368     joinPool(e);
369     }
370 dl 1.8 }
371    
372     /**
373     * ThreadPoolExecutor using privilegedThreadFactory has
374     * specified group, priority, daemon status, name,
375     * access control context and context class loader
376     */
377     public void testPrivilegedThreadFactory() {
378 dl 1.14 Policy savedPolicy = null;
379     try {
380     savedPolicy = Policy.getPolicy();
381     AdjustablePolicy policy = new AdjustablePolicy();
382     policy.addPermission(new RuntimePermission("getContextClassLoader"));
383     policy.addPermission(new RuntimePermission("setContextClassLoader"));
384     Policy.setPolicy(policy);
385     } catch (AccessControlException ok) {
386     return;
387     }
388 tim 1.9 final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
389     final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
390 dl 1.8 final AccessControlContext thisacc = AccessController.getContext();
391 tim 1.9 Runnable r = new Runnable() {
392     public void run() {
393 dl 1.13 try {
394     Thread current = Thread.currentThread();
395     threadAssertTrue(!current.isDaemon());
396 dl 1.17 threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
397 dl 1.13 ThreadGroup g = current.getThreadGroup();
398     SecurityManager s = System.getSecurityManager();
399     if (s != null)
400     threadAssertTrue(g == s.getThreadGroup());
401     else
402     threadAssertTrue(g == egroup);
403     String name = current.getName();
404     threadAssertTrue(name.endsWith("thread-1"));
405     threadAssertTrue(thisccl == current.getContextClassLoader());
406     threadAssertTrue(thisacc.equals(AccessController.getContext()));
407     } catch(SecurityException ok) {
408     // Also pass if not allowed to change settings
409     }
410 dl 1.14 }
411 tim 1.9 };
412     ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
413    
414     Policy.setPolicy(savedPolicy);
415     e.execute(r);
416 dl 1.14 try {
417     e.shutdown();
418     } catch(SecurityException ok) {
419     }
420 tim 1.9 try {
421     Thread.sleep(SHORT_DELAY_MS);
422     } catch (Exception ex) {
423     unexpectedException();
424     } finally {
425     joinPool(e);
426     }
427 dl 1.1
428 dl 1.8 }
429 dl 1.11
430 dl 1.16 void checkCCL() {
431 dl 1.18 SecurityManager sm = System.getSecurityManager();
432     if (sm != null) {
433     sm.checkPermission(new RuntimePermission("setContextClassLoader"));
434     sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
435     }
436 dl 1.16 }
437    
438     class CheckCCL implements Callable<Object> {
439 dl 1.11 public Object call() {
440 dl 1.16 checkCCL();
441 dl 1.11 return null;
442     }
443     }
444    
445    
446     /**
447     * Without class loader permissions, creating
448     * privilegedCallableUsingCurrentClassLoader throws ACE
449     */
450     public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
451 dl 1.14 Policy savedPolicy = null;
452     try {
453     savedPolicy = Policy.getPolicy();
454     AdjustablePolicy policy = new AdjustablePolicy();
455     Policy.setPolicy(policy);
456     } catch (AccessControlException ok) {
457     return;
458     }
459    
460 dl 1.16 // Check if program still has too many permissions to run test
461     try {
462     checkCCL();
463     // too many privileges to test; so return
464     Policy.setPolicy(savedPolicy);
465     return;
466     } catch(AccessControlException ok) {
467     }
468    
469 dl 1.11 try {
470     Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
471     shouldThrow();
472     } catch(AccessControlException success) {
473     } catch(Exception ex) {
474     unexpectedException();
475     }
476     finally {
477     Policy.setPolicy(savedPolicy);
478     }
479     }
480    
481     /**
482 dl 1.16 * With class loader permissions, calling
483     * privilegedCallableUsingCurrentClassLoader does not throw ACE
484 dl 1.11 */
485     public void testprivilegedCallableUsingCCLWithPrivs() {
486 dl 1.14 Policy savedPolicy = null;
487     try {
488     savedPolicy = Policy.getPolicy();
489     AdjustablePolicy policy = new AdjustablePolicy();
490     policy.addPermission(new RuntimePermission("getContextClassLoader"));
491     policy.addPermission(new RuntimePermission("setContextClassLoader"));
492     Policy.setPolicy(policy);
493     } catch (AccessControlException ok) {
494     return;
495     }
496    
497 dl 1.11 try {
498     Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
499     task.call();
500     } catch(Exception ex) {
501     unexpectedException();
502     }
503     finally {
504     Policy.setPolicy(savedPolicy);
505     }
506     }
507    
508     /**
509     * Without permissions, calling privilegedCallable throws ACE
510     */
511     public void testprivilegedCallableWithNoPrivs() {
512 dl 1.16 Callable task;
513     Policy savedPolicy = null;
514     AdjustablePolicy policy = null;
515     AccessControlContext noprivAcc = null;
516 dl 1.14 try {
517 dl 1.16 savedPolicy = Policy.getPolicy();
518     policy = new AdjustablePolicy();
519 dl 1.14 Policy.setPolicy(policy);
520 dl 1.16 noprivAcc = AccessController.getContext();
521     task = Executors.privilegedCallable(new CheckCCL());
522 dl 1.15 Policy.setPolicy(savedPolicy);
523 dl 1.14 } catch (AccessControlException ok) {
524 dl 1.16 return; // program has too few permissions to set up test
525     }
526    
527     // Make sure that program doesn't have too many permissions
528     try {
529     AccessController.doPrivileged(new PrivilegedAction() {
530     public Object run() {
531     checkCCL();
532     return null;
533     }}, noprivAcc);
534     // too many permssions; skip test
535 dl 1.14 return;
536 dl 1.16 } catch(AccessControlException ok) {
537 dl 1.14 }
538    
539 dl 1.11 try {
540 dl 1.16 task.call();
541     shouldThrow();
542     } catch(AccessControlException success) {
543 dl 1.11 } catch(Exception ex) {
544     unexpectedException();
545 dl 1.15 }
546 dl 1.11 }
547    
548     /**
549     * With permissions, calling privilegedCallable succeeds
550     */
551     public void testprivilegedCallableWithPrivs() {
552 dl 1.14 Policy savedPolicy = null;
553     try {
554     savedPolicy = Policy.getPolicy();
555     AdjustablePolicy policy = new AdjustablePolicy();
556     policy.addPermission(new RuntimePermission("getContextClassLoader"));
557     policy.addPermission(new RuntimePermission("setContextClassLoader"));
558     Policy.setPolicy(policy);
559     } catch (AccessControlException ok) {
560     return;
561     }
562    
563 dl 1.11 Callable task = Executors.privilegedCallable(new CheckCCL());
564     try {
565     task.call();
566     } catch(Exception ex) {
567     unexpectedException();
568     } finally {
569     Policy.setPolicy(savedPolicy);
570     }
571     }
572    
573     /**
574     * callable(Runnable) returns null when called
575     */
576     public void testCallable1() {
577     try {
578     Callable c = Executors.callable(new NoOpRunnable());
579     assertNull(c.call());
580     } catch(Exception ex) {
581     unexpectedException();
582     }
583    
584     }
585    
586     /**
587     * callable(Runnable, result) returns result when called
588     */
589     public void testCallable2() {
590     try {
591     Callable c = Executors.callable(new NoOpRunnable(), one);
592     assertEquals(one, c.call());
593     } catch(Exception ex) {
594     unexpectedException();
595     }
596     }
597    
598     /**
599     * callable(PrivilegedAction) returns its result when called
600     */
601     public void testCallable3() {
602     try {
603     Callable c = Executors.callable(new PrivilegedAction() {
604     public Object run() { return one; }});
605     assertEquals(one, c.call());
606     } catch(Exception ex) {
607     unexpectedException();
608     }
609     }
610    
611     /**
612     * callable(PrivilegedExceptionAction) returns its result when called
613     */
614     public void testCallable4() {
615     try {
616     Callable c = Executors.callable(new PrivilegedExceptionAction() {
617     public Object run() { return one; }});
618     assertEquals(one, c.call());
619     } catch(Exception ex) {
620     unexpectedException();
621     }
622     }
623    
624    
625     /**
626     * callable(null Runnable) throws NPE
627     */
628     public void testCallableNPE1() {
629     try {
630     Runnable r = null;
631     Callable c = Executors.callable(r);
632     } catch (NullPointerException success) {
633     }
634     }
635    
636     /**
637     * callable(null, result) throws NPE
638     */
639     public void testCallableNPE2() {
640     try {
641     Runnable r = null;
642     Callable c = Executors.callable(r, one);
643     } catch (NullPointerException success) {
644     }
645     }
646    
647     /**
648     * callable(null PrivilegedAction) throws NPE
649     */
650     public void testCallableNPE3() {
651     try {
652     PrivilegedAction r = null;
653     Callable c = Executors.callable(r);
654     } catch (NullPointerException success) {
655     }
656     }
657    
658     /**
659     * callable(null PrivilegedExceptionAction) throws NPE
660     */
661     public void testCallableNPE4() {
662     try {
663     PrivilegedExceptionAction r = null;
664     Callable c = Executors.callable(r);
665     } catch (NullPointerException success) {
666     }
667     }
668    
669 dl 1.1
670     }