ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorsTest.java
Revision: 1.40
Committed: Fri May 27 19:28:38 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.39: +20 -29 lines
Log Message:
improve testTimedCallable

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 jsr166 1.37 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.20 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9     import junit.framework.*;
10     import java.util.*;
11     import java.util.concurrent.*;
12 jsr166 1.26 import static java.util.concurrent.TimeUnit.MILLISECONDS;
13 dl 1.2 import java.math.BigInteger;
14 dl 1.8 import java.security.*;
15 dl 1.1
16 jsr166 1.22 public class ExecutorsTest extends JSR166TestCase {
17 dl 1.1 public static void main(String[] args) {
18 jsr166 1.30 junit.textui.TestRunner.run(suite());
19 dl 1.1 }
20     public static Test suite() {
21 tim 1.9 return new TestSuite(ExecutorsTest.class);
22 dl 1.1 }
23    
24 dl 1.5 /**
25     * A newCachedThreadPool can execute runnables
26     */
27     public void testNewCachedThreadPool1() {
28     ExecutorService e = Executors.newCachedThreadPool();
29     e.execute(new NoOpRunnable());
30     e.execute(new NoOpRunnable());
31     e.execute(new NoOpRunnable());
32 dl 1.14 joinPool(e);
33 dl 1.5 }
34    
35     /**
36     * A newCachedThreadPool with given ThreadFactory can execute runnables
37     */
38     public void testNewCachedThreadPool2() {
39 dl 1.6 ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
40 dl 1.5 e.execute(new NoOpRunnable());
41     e.execute(new NoOpRunnable());
42     e.execute(new NoOpRunnable());
43 dl 1.14 joinPool(e);
44 dl 1.5 }
45    
46     /**
47     * A newCachedThreadPool with null ThreadFactory throws NPE
48     */
49     public void testNewCachedThreadPool3() {
50     try {
51     ExecutorService e = Executors.newCachedThreadPool(null);
52     shouldThrow();
53 jsr166 1.23 } catch (NullPointerException success) {}
54 dl 1.5 }
55    
56     /**
57     * A new SingleThreadExecutor can execute runnables
58     */
59     public void testNewSingleThreadExecutor1() {
60     ExecutorService e = Executors.newSingleThreadExecutor();
61     e.execute(new NoOpRunnable());
62     e.execute(new NoOpRunnable());
63     e.execute(new NoOpRunnable());
64 dl 1.14 joinPool(e);
65 dl 1.5 }
66    
67     /**
68     * A new SingleThreadExecutor with given ThreadFactory can execute runnables
69     */
70     public void testNewSingleThreadExecutor2() {
71 dl 1.6 ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
72 dl 1.5 e.execute(new NoOpRunnable());
73     e.execute(new NoOpRunnable());
74     e.execute(new NoOpRunnable());
75 dl 1.14 joinPool(e);
76 dl 1.5 }
77    
78     /**
79     * A new SingleThreadExecutor with null ThreadFactory throws NPE
80     */
81     public void testNewSingleThreadExecutor3() {
82     try {
83     ExecutorService e = Executors.newSingleThreadExecutor(null);
84     shouldThrow();
85 jsr166 1.23 } catch (NullPointerException success) {}
86 dl 1.5 }
87    
88     /**
89 dl 1.11 * A new SingleThreadExecutor cannot be casted to concrete implementation
90     */
91     public void testCastNewSingleThreadExecutor() {
92     ExecutorService e = Executors.newSingleThreadExecutor();
93     try {
94     ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
95 jsr166 1.23 shouldThrow();
96 dl 1.11 } catch (ClassCastException success) {
97     } finally {
98     joinPool(e);
99     }
100     }
101    
102     /**
103 dl 1.5 * A new newFixedThreadPool can execute runnables
104     */
105     public void testNewFixedThreadPool1() {
106     ExecutorService e = Executors.newFixedThreadPool(2);
107     e.execute(new NoOpRunnable());
108     e.execute(new NoOpRunnable());
109     e.execute(new NoOpRunnable());
110 dl 1.14 joinPool(e);
111 dl 1.5 }
112    
113     /**
114     * A new newFixedThreadPool with given ThreadFactory can execute runnables
115     */
116     public void testNewFixedThreadPool2() {
117 dl 1.6 ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
118 dl 1.5 e.execute(new NoOpRunnable());
119     e.execute(new NoOpRunnable());
120     e.execute(new NoOpRunnable());
121 dl 1.14 joinPool(e);
122 dl 1.5 }
123    
124     /**
125     * A new newFixedThreadPool with null ThreadFactory throws NPE
126     */
127     public void testNewFixedThreadPool3() {
128     try {
129     ExecutorService e = Executors.newFixedThreadPool(2, null);
130     shouldThrow();
131 jsr166 1.23 } catch (NullPointerException success) {}
132 dl 1.5 }
133    
134     /**
135     * A new newFixedThreadPool with 0 threads throws IAE
136     */
137     public void testNewFixedThreadPool4() {
138     try {
139     ExecutorService e = Executors.newFixedThreadPool(0);
140     shouldThrow();
141 jsr166 1.23 } catch (IllegalArgumentException success) {}
142 dl 1.5 }
143 dl 1.1
144 dl 1.2 /**
145 dl 1.11 * An unconfigurable newFixedThreadPool can execute runnables
146     */
147     public void testunconfigurableExecutorService() {
148     ExecutorService e = Executors.unconfigurableExecutorService(Executors.newFixedThreadPool(2));
149     e.execute(new NoOpRunnable());
150     e.execute(new NoOpRunnable());
151     e.execute(new NoOpRunnable());
152 dl 1.14 joinPool(e);
153 dl 1.11 }
154    
155     /**
156     * unconfigurableExecutorService(null) throws NPE
157     */
158     public void testunconfigurableExecutorServiceNPE() {
159     try {
160     ExecutorService e = Executors.unconfigurableExecutorService(null);
161 jsr166 1.23 shouldThrow();
162     } catch (NullPointerException success) {}
163 dl 1.11 }
164    
165     /**
166     * unconfigurableScheduledExecutorService(null) throws NPE
167     */
168     public void testunconfigurableScheduledExecutorServiceNPE() {
169     try {
170     ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
171 jsr166 1.23 shouldThrow();
172     } catch (NullPointerException success) {}
173 dl 1.11 }
174    
175     /**
176     * a newSingleThreadScheduledExecutor successfully runs delayed task
177     */
178 jsr166 1.23 public void testNewSingleThreadScheduledExecutor() throws Exception {
179 jsr166 1.35 ScheduledExecutorService p = Executors.newSingleThreadScheduledExecutor();
180     try {
181     final CountDownLatch done = new CountDownLatch(1);
182     final Runnable task = new CheckedRunnable() {
183     public void realRun() {
184     done.countDown();
185     }};
186     Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
187     SHORT_DELAY_MS, MILLISECONDS);
188     assertFalse(f.isDone());
189 jsr166 1.36 assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
190     assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
191     assertSame(Boolean.TRUE, f.get());
192 jsr166 1.35 assertTrue(f.isDone());
193     } finally {
194     joinPool(p);
195     }
196 dl 1.11 }
197    
198     /**
199     * a newScheduledThreadPool successfully runs delayed task
200     */
201 jsr166 1.23 public void testnewScheduledThreadPool() throws Exception {
202 jsr166 1.35 ScheduledExecutorService p = Executors.newScheduledThreadPool(2);
203     try {
204     final CountDownLatch done = new CountDownLatch(1);
205     final Runnable task = new CheckedRunnable() {
206     public void realRun() {
207     done.countDown();
208     }};
209     Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
210     SHORT_DELAY_MS, MILLISECONDS);
211     assertFalse(f.isDone());
212 jsr166 1.36 assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
213     assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
214     assertSame(Boolean.TRUE, f.get());
215 jsr166 1.35 assertTrue(f.isDone());
216     } finally {
217     joinPool(p);
218     }
219 dl 1.11 }
220    
221     /**
222 jsr166 1.24 * an unconfigurable newScheduledThreadPool successfully runs delayed task
223 dl 1.11 */
224 jsr166 1.23 public void testunconfigurableScheduledExecutorService() throws Exception {
225 jsr166 1.35 ScheduledExecutorService p =
226     Executors.unconfigurableScheduledExecutorService
227     (Executors.newScheduledThreadPool(2));
228     try {
229     final CountDownLatch done = new CountDownLatch(1);
230     final Runnable task = new CheckedRunnable() {
231     public void realRun() {
232     done.countDown();
233     }};
234     Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
235     SHORT_DELAY_MS, MILLISECONDS);
236     assertFalse(f.isDone());
237 jsr166 1.36 assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
238     assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
239     assertSame(Boolean.TRUE, f.get());
240 jsr166 1.35 assertTrue(f.isDone());
241     } finally {
242     joinPool(p);
243     }
244 dl 1.11 }
245    
246     /**
247 jsr166 1.34 * Future.get on submitted tasks will time out if they compute too long.
248 dl 1.2 */
249 jsr166 1.23 public void testTimedCallable() throws Exception {
250 jsr166 1.40 final ExecutorService[] executors = {
251     Executors.newSingleThreadExecutor(),
252     Executors.newCachedThreadPool(),
253     Executors.newFixedThreadPool(2),
254     Executors.newScheduledThreadPool(2),
255     };
256    
257 jsr166 1.33 final Runnable sleeper = new CheckedInterruptedRunnable() {
258     public void realRun() throws InterruptedException {
259 dl 1.39 delay(LONG_DELAY_MS);
260 jsr166 1.33 }};
261 jsr166 1.40
262     List<Thread> threads = new ArrayList<Thread>();
263     for (final ExecutorService executor : executors) {
264     threads.add(newStartedThread(new CheckedRunnable() {
265     public void realRun() {
266     long startTime = System.nanoTime();
267     Future future = executor.submit(sleeper);
268     assertFutureTimesOut(future);
269     }}));
270 dl 1.2 }
271 jsr166 1.40 for (Thread thread : threads)
272     awaitTermination(thread);
273     for (ExecutorService executor : executors)
274     joinPool(executor);
275 dl 1.2 }
276    
277 dl 1.8 /**
278     * ThreadPoolExecutor using defaultThreadFactory has
279     * specified group, priority, daemon status, and name
280     */
281 jsr166 1.23 public void testDefaultThreadFactory() throws Exception {
282 tim 1.9 final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
283 jsr166 1.31 Runnable r = new CheckedRunnable() {
284     public void realRun() {
285     try {
286     Thread current = Thread.currentThread();
287     assertTrue(!current.isDaemon());
288     assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
289     ThreadGroup g = current.getThreadGroup();
290     SecurityManager s = System.getSecurityManager();
291     if (s != null)
292     assertTrue(g == s.getThreadGroup());
293     else
294     assertTrue(g == egroup);
295     String name = current.getName();
296     assertTrue(name.endsWith("thread-1"));
297     } catch (SecurityException ok) {
298     // Also pass if not allowed to change setting
299 tim 1.9 }
300 jsr166 1.31 }};
301 tim 1.9 ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
302 jsr166 1.20
303 tim 1.9 e.execute(r);
304 dl 1.14 try {
305     e.shutdown();
306 jsr166 1.21 } catch (SecurityException ok) {
307 dl 1.14 }
308 jsr166 1.20
309 tim 1.9 try {
310 dl 1.39 delay(SHORT_DELAY_MS);
311 tim 1.9 } finally {
312     joinPool(e);
313     }
314 dl 1.8 }
315    
316     /**
317     * ThreadPoolExecutor using privilegedThreadFactory has
318     * specified group, priority, daemon status, name,
319     * access control context and context class loader
320     */
321 jsr166 1.23 public void testPrivilegedThreadFactory() throws Exception {
322 jsr166 1.29 Runnable r = new CheckedRunnable() {
323     public void realRun() throws Exception {
324     final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
325     final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
326     final AccessControlContext thisacc = AccessController.getContext();
327     Runnable r = new CheckedRunnable() {
328     public void realRun() {
329 jsr166 1.25 Thread current = Thread.currentThread();
330 jsr166 1.29 assertTrue(!current.isDaemon());
331     assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
332 jsr166 1.25 ThreadGroup g = current.getThreadGroup();
333     SecurityManager s = System.getSecurityManager();
334     if (s != null)
335 jsr166 1.29 assertTrue(g == s.getThreadGroup());
336 jsr166 1.25 else
337 jsr166 1.29 assertTrue(g == egroup);
338 jsr166 1.25 String name = current.getName();
339 jsr166 1.29 assertTrue(name.endsWith("thread-1"));
340 jsr166 1.31 assertSame(thisccl, current.getContextClassLoader());
341     assertEquals(thisacc, AccessController.getContext());
342 jsr166 1.29 }};
343     ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
344     e.execute(r);
345     e.shutdown();
346 dl 1.39 delay(SHORT_DELAY_MS);
347 jsr166 1.29 joinPool(e);
348     }};
349    
350     runWithPermissions(r,
351     new RuntimePermission("getClassLoader"),
352     new RuntimePermission("setContextClassLoader"),
353     new RuntimePermission("modifyThread"));
354     }
355 jsr166 1.20
356 jsr166 1.29 boolean haveCCLPermissions() {
357     SecurityManager sm = System.getSecurityManager();
358     if (sm != null) {
359     try {
360     sm.checkPermission(new RuntimePermission("setContextClassLoader"));
361     sm.checkPermission(new RuntimePermission("getClassLoader"));
362     } catch (AccessControlException e) {
363     return false;
364     }
365 tim 1.9 }
366 jsr166 1.29 return true;
367 dl 1.8 }
368 dl 1.11
369 dl 1.16 void checkCCL() {
370 dl 1.18 SecurityManager sm = System.getSecurityManager();
371     if (sm != null) {
372     sm.checkPermission(new RuntimePermission("setContextClassLoader"));
373 jsr166 1.19 sm.checkPermission(new RuntimePermission("getClassLoader"));
374 dl 1.18 }
375 dl 1.16 }
376    
377     class CheckCCL implements Callable<Object> {
378 dl 1.11 public Object call() {
379 dl 1.16 checkCCL();
380 dl 1.11 return null;
381     }
382     }
383    
384     /**
385     * Without class loader permissions, creating
386     * privilegedCallableUsingCurrentClassLoader throws ACE
387     */
388     public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
389 jsr166 1.29 Runnable r = new CheckedRunnable() {
390     public void realRun() throws Exception {
391     if (System.getSecurityManager() == null)
392     return;
393     try {
394     Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
395     shouldThrow();
396     } catch (AccessControlException success) {}
397     }};
398 dl 1.16
399 jsr166 1.29 runWithoutPermissions(r);
400 dl 1.11 }
401    
402     /**
403 dl 1.16 * With class loader permissions, calling
404     * privilegedCallableUsingCurrentClassLoader does not throw ACE
405 dl 1.11 */
406 jsr166 1.23 public void testprivilegedCallableUsingCCLWithPrivs() throws Exception {
407 jsr166 1.29 Runnable r = new CheckedRunnable() {
408     public void realRun() throws Exception {
409     Executors.privilegedCallableUsingCurrentClassLoader
410     (new NoOpCallable())
411     .call();
412     }};
413    
414     runWithPermissions(r,
415     new RuntimePermission("getClassLoader"),
416     new RuntimePermission("setContextClassLoader"));
417 dl 1.11 }
418    
419     /**
420     * Without permissions, calling privilegedCallable throws ACE
421     */
422 jsr166 1.23 public void testprivilegedCallableWithNoPrivs() throws Exception {
423 jsr166 1.32 // Avoid classloader-related SecurityExceptions in swingui.TestRunner
424     Executors.privilegedCallable(new CheckCCL());
425    
426 jsr166 1.29 Runnable r = new CheckedRunnable() {
427     public void realRun() throws Exception {
428     if (System.getSecurityManager() == null)
429     return;
430     Callable task = Executors.privilegedCallable(new CheckCCL());
431     try {
432     task.call();
433     shouldThrow();
434     } catch (AccessControlException success) {}
435     }};
436    
437     runWithoutPermissions(r);
438    
439     // It seems rather difficult to test that the
440     // AccessControlContext of the privilegedCallable is used
441     // instead of its caller. Below is a failed attempt to do
442     // that, which does not work because the AccessController
443     // cannot capture the internal state of the current Policy.
444     // It would be much more work to differentiate based on,
445     // e.g. CodeSource.
446    
447     // final AccessControlContext[] noprivAcc = new AccessControlContext[1];
448     // final Callable[] task = new Callable[1];
449    
450     // runWithPermissions
451     // (new CheckedRunnable() {
452     // public void realRun() {
453     // if (System.getSecurityManager() == null)
454     // return;
455     // noprivAcc[0] = AccessController.getContext();
456     // task[0] = Executors.privilegedCallable(new CheckCCL());
457     // try {
458     // AccessController.doPrivileged(new PrivilegedAction<Void>() {
459     // public Void run() {
460     // checkCCL();
461     // return null;
462     // }}, noprivAcc[0]);
463     // shouldThrow();
464     // } catch (AccessControlException success) {}
465     // }});
466    
467     // runWithPermissions
468     // (new CheckedRunnable() {
469     // public void realRun() throws Exception {
470     // if (System.getSecurityManager() == null)
471     // return;
472     // // Verify that we have an underprivileged ACC
473     // try {
474     // AccessController.doPrivileged(new PrivilegedAction<Void>() {
475     // public Void run() {
476     // checkCCL();
477     // return null;
478     // }}, noprivAcc[0]);
479     // shouldThrow();
480     // } catch (AccessControlException success) {}
481    
482     // try {
483     // task[0].call();
484     // shouldThrow();
485     // } catch (AccessControlException success) {}
486     // }},
487     // new RuntimePermission("getClassLoader"),
488     // new RuntimePermission("setContextClassLoader"));
489 dl 1.11 }
490    
491     /**
492     * With permissions, calling privilegedCallable succeeds
493     */
494 jsr166 1.23 public void testprivilegedCallableWithPrivs() throws Exception {
495 jsr166 1.29 Runnable r = new CheckedRunnable() {
496     public void realRun() throws Exception {
497     Executors.privilegedCallable(new CheckCCL()).call();
498     }};
499    
500 jsr166 1.38 runWithPermissions(r,
501 jsr166 1.29 new RuntimePermission("getClassLoader"),
502     new RuntimePermission("setContextClassLoader"));
503 dl 1.11 }
504    
505     /**
506     * callable(Runnable) returns null when called
507 jsr166 1.20 */
508 jsr166 1.23 public void testCallable1() throws Exception {
509     Callable c = Executors.callable(new NoOpRunnable());
510     assertNull(c.call());
511 dl 1.11 }
512    
513     /**
514     * callable(Runnable, result) returns result when called
515 jsr166 1.20 */
516 jsr166 1.23 public void testCallable2() throws Exception {
517     Callable c = Executors.callable(new NoOpRunnable(), one);
518 jsr166 1.27 assertSame(one, c.call());
519 dl 1.11 }
520    
521     /**
522     * callable(PrivilegedAction) returns its result when called
523 jsr166 1.20 */
524 jsr166 1.23 public void testCallable3() throws Exception {
525     Callable c = Executors.callable(new PrivilegedAction() {
526     public Object run() { return one; }});
527 jsr166 1.27 assertSame(one, c.call());
528 dl 1.11 }
529    
530     /**
531     * callable(PrivilegedExceptionAction) returns its result when called
532 jsr166 1.20 */
533 jsr166 1.23 public void testCallable4() throws Exception {
534     Callable c = Executors.callable(new PrivilegedExceptionAction() {
535     public Object run() { return one; }});
536 jsr166 1.27 assertSame(one, c.call());
537 dl 1.11 }
538    
539     /**
540     * callable(null Runnable) throws NPE
541 jsr166 1.20 */
542 dl 1.11 public void testCallableNPE1() {
543     try {
544 jsr166 1.23 Callable c = Executors.callable((Runnable) null);
545     shouldThrow();
546     } catch (NullPointerException success) {}
547 dl 1.11 }
548    
549     /**
550     * callable(null, result) throws NPE
551 jsr166 1.20 */
552 dl 1.11 public void testCallableNPE2() {
553     try {
554 jsr166 1.23 Callable c = Executors.callable((Runnable) null, one);
555     shouldThrow();
556     } catch (NullPointerException success) {}
557 dl 1.11 }
558    
559     /**
560     * callable(null PrivilegedAction) throws NPE
561 jsr166 1.20 */
562 dl 1.11 public void testCallableNPE3() {
563     try {
564 jsr166 1.23 Callable c = Executors.callable((PrivilegedAction) null);
565     shouldThrow();
566     } catch (NullPointerException success) {}
567 dl 1.11 }
568    
569     /**
570     * callable(null PrivilegedExceptionAction) throws NPE
571 jsr166 1.20 */
572 dl 1.11 public void testCallableNPE4() {
573     try {
574 jsr166 1.23 Callable c = Executors.callable((PrivilegedExceptionAction) null);
575     shouldThrow();
576     } catch (NullPointerException success) {}
577 dl 1.11 }
578    
579 dl 1.1 }