ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorsTest.java
Revision: 1.26
Committed: Sat Nov 21 02:33:20 2009 UTC (14 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.25: +5 -4 lines
Log Message:
import static TimeUnit.MILLISECONDS

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