ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorsTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ExecutorsTest.java (file contents):
Revision 1.8 by dl, Sat Nov 1 18:37:02 2003 UTC vs.
Revision 1.18 by dl, Tue Aug 4 13:58:09 2009 UTC

# Line 1 | Line 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.
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 > * http://creativecommons.org/licenses/publicdomain
5 > * Other contributors include Andrew Wright, Jeffrey Hayes,
6 > * Pat Fisher, Mike Judd.
7   */
8  
9  
# Line 11 | Line 12 | import java.util.*;
12   import java.util.concurrent.*;
13   import java.math.BigInteger;
14   import java.security.*;
15 + import sun.security.util.SecurityConstants;
16  
17   public class ExecutorsTest extends JSR166TestCase{
18      public static void main(String[] args) {
19 <        junit.textui.TestRunner.run (suite());  
19 >        junit.textui.TestRunner.run (suite());  
20      }
21      public static Test suite() {
22 <        return new TestSuite(ExecutorsTest.class);
21 <    }
22 <
23 <    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 <        }
22 >        return new TestSuite(ExecutorsTest.class);
23      }
24  
25      static class TimedCallable<T> implements Callable<T> {
26 <        private final Executor exec;
26 >        private final ExecutorService exec;
27          private final Callable<T> func;
28          private final long msecs;
29          
30 <        TimedCallable(Executor exec, Callable<T> func, long msecs) {
30 >        TimedCallable(ExecutorService exec, Callable<T> func, long msecs) {
31              this.exec = exec;
32              this.func = func;
33              this.msecs = msecs;
34          }
35          
36          public T call() throws Exception {
37 <            Future<T> ftask = Executors.execute(exec, func);
37 >            Future<T> ftask = exec.submit(func);
38              try {
39                  return ftask.get(msecs, TimeUnit.MILLISECONDS);
40              } finally {
# Line 80 | Line 70 | public class ExecutorsTest extends JSR16
70          e.execute(new NoOpRunnable());
71          e.execute(new NoOpRunnable());
72          e.execute(new NoOpRunnable());
73 <        e.shutdown();
73 >        joinPool(e);
74      }
75  
76      /**
# Line 91 | Line 81 | public class ExecutorsTest extends JSR16
81          e.execute(new NoOpRunnable());
82          e.execute(new NoOpRunnable());
83          e.execute(new NoOpRunnable());
84 <        e.shutdown();
84 >        joinPool(e);
85      }
86  
87      /**
# Line 115 | Line 105 | public class ExecutorsTest extends JSR16
105          e.execute(new NoOpRunnable());
106          e.execute(new NoOpRunnable());
107          e.execute(new NoOpRunnable());
108 <        e.shutdown();
108 >        joinPool(e);
109      }
110  
111      /**
# Line 126 | Line 116 | public class ExecutorsTest extends JSR16
116          e.execute(new NoOpRunnable());
117          e.execute(new NoOpRunnable());
118          e.execute(new NoOpRunnable());
119 <        e.shutdown();
119 >        joinPool(e);
120      }
121  
122      /**
# Line 142 | Line 132 | public class ExecutorsTest extends JSR16
132      }
133  
134      /**
135 +     * 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       * A new newFixedThreadPool can execute runnables
150       */
151      public void testNewFixedThreadPool1() {
# Line 149 | Line 153 | public class ExecutorsTest extends JSR16
153          e.execute(new NoOpRunnable());
154          e.execute(new NoOpRunnable());
155          e.execute(new NoOpRunnable());
156 <        e.shutdown();
156 >        joinPool(e);
157      }
158  
159      /**
# Line 160 | Line 164 | public class ExecutorsTest extends JSR16
164          e.execute(new NoOpRunnable());
165          e.execute(new NoOpRunnable());
166          e.execute(new NoOpRunnable());
167 <        e.shutdown();
167 >        joinPool(e);
168      }
169  
170      /**
# Line 187 | Line 191 | public class ExecutorsTest extends JSR16
191          }
192      }
193  
194 +
195      /**
196 <     * execute of runnable runs it to completion
196 >     * An unconfigurable newFixedThreadPool can execute runnables
197       */
198 <    public void testExecuteRunnable() {
199 <        try {
200 <            Executor e = new DirectExecutor();
201 <            TrackedShortRunnable task = new TrackedShortRunnable();
202 <            assertFalse(task.done);
203 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
199 <            String result = future.get();
200 <            assertTrue(task.done);
201 <            assertSame(TEST_STRING, result);
202 <        }
203 <        catch (ExecutionException ex) {
204 <            unexpectedException();
205 <        }
206 <        catch (InterruptedException ex) {
207 <            unexpectedException();
208 <        }
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 >        joinPool(e);
204      }
205  
206      /**
207 <     * invoke of a runnable runs it to completion
207 >     * unconfigurableExecutorService(null) throws NPE
208       */
209 <    public void testInvokeRunnable() {
209 >    public void testunconfigurableExecutorServiceNPE() {
210          try {
211 <            Executor e = new DirectExecutor();
217 <            TrackedShortRunnable task = new TrackedShortRunnable();
218 <            assertFalse(task.done);
219 <            Executors.invoke(e, task);
220 <            assertTrue(task.done);
211 >            ExecutorService e = Executors.unconfigurableExecutorService(null);
212          }
213 <        catch (ExecutionException ex) {
223 <            unexpectedException();
224 <        }
225 <        catch (InterruptedException ex) {
226 <            unexpectedException();
213 >        catch (NullPointerException success) {
214          }
215      }
216  
217      /**
218 <     * execute of a callable runs it to completion
218 >     * unconfigurableScheduledExecutorService(null) throws NPE
219       */
220 <    public void testExecuteCallable() {
220 >    public void testunconfigurableScheduledExecutorServiceNPE() {
221          try {
222 <            Executor e = new DirectExecutor();
236 <            Future<String> future = Executors.execute(e, new StringTask());
237 <            String result = future.get();
238 <            assertSame(TEST_STRING, result);
222 >            ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
223          }
224 <        catch (ExecutionException ex) {
241 <            unexpectedException();
242 <        }
243 <        catch (InterruptedException ex) {
244 <            unexpectedException();
224 >        catch (NullPointerException success) {
225          }
226      }
227  
228  
229      /**
230 <     * execute of a privileged action runs it to completion
230 >     * a newSingleThreadScheduledExecutor successfully runs delayed task
231       */
232 <    public void testExecutePrivilegedAction() {
233 <        Policy savedPolicy = Policy.getPolicy();
234 <        AdjustablePolicy policy = new AdjustablePolicy();
235 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
236 <        policy.addPermission(new RuntimePermission("setContextClassLoader"));
237 <        Policy.setPolicy(policy);
238 <        try {
239 <            Executor e = new DirectExecutor();
240 <            Future future = Executors.execute(e, new PrivilegedAction() {
241 <                    public Object run() {
242 <                        return TEST_STRING;
243 <                    }});
244 <
265 <            Object result = future.get();
266 <            assertSame(TEST_STRING, result);
267 <        }
268 <        catch (ExecutionException ex) {
269 <            unexpectedException();
270 <        }
271 <        catch (InterruptedException ex) {
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          }
274        finally {
275            Policy.setPolicy(savedPolicy);
276        }
247      }
248  
249      /**
250 <     * execute of a privileged exception action runs it to completion
250 >     * a newScheduledThreadPool successfully runs delayed task
251       */
252 <    public void testExecutePrivilegedExceptionAction() {
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 PrivilegedExceptionAction() {
261 <                    public Object run() {
262 <                        return TEST_STRING;
263 <                    }});
264 <
295 <            Object result = future.get();
296 <            assertSame(TEST_STRING, result);
297 <        }
298 <        catch (ExecutionException ex) {
299 <            unexpectedException();
300 <        }
301 <        catch (InterruptedException ex) {
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          }
304        finally {
305            Policy.setPolicy(savedPolicy);
306        }
267      }
268  
269      /**
270 <     * execute of a failed privileged exception action reports exception
270 >     * an unconfigurable  newScheduledThreadPool successfully runs delayed task
271       */
272 <    public void testExecuteFailedPrivilegedExceptionAction() {
273 <        Policy savedPolicy = Policy.getPolicy();
274 <        AdjustablePolicy policy = new AdjustablePolicy();
275 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
276 <        policy.addPermission(new RuntimePermission("setContextClassLoader"));
277 <        Policy.setPolicy(policy);
278 <        try {
279 <            Executor e = new DirectExecutor();
280 <            Future future = Executors.execute(e, new PrivilegedExceptionAction() {
281 <                    public Object run() throws Exception {
282 <                        throw new IndexOutOfBoundsException();
283 <                    }});
284 <
325 <            Object result = future.get();
326 <            shouldThrow();
327 <        }
328 <        catch (ExecutionException success) {
329 <        }
330 <        catch (InterruptedException ex) {
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          }
333        finally {
334            Policy.setPolicy(savedPolicy);
335        }
287      }
288  
289      /**
290 <     * invoke of a collable runs it to completion
290 >     *  timeouts from execute will time out if they compute too long.
291       */
292 <    public void testInvokeCallable() {
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 <            Executor e = new DirectExecutor();
298 <            String result = Executors.invoke(e, new StringTask());
299 <
300 <            assertSame(TEST_STRING, result);
301 <        }
302 <        catch (ExecutionException ex) {
303 <            unexpectedException();
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 >                    unexpectedException();
318 >                }
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 <        catch (InterruptedException ex) {
325 <            unexpectedException();
324 >        finally {
325 >            joinPool(executor);
326          }
327      }
328  
329 +    
330      /**
331 <     * execute with null executor throws NPE
331 >     * ThreadPoolExecutor using defaultThreadFactory has
332 >     * specified group, priority, daemon status, and name
333       */
334 <    public void testNullExecuteRunnable() {
334 >    public void testDefaultThreadFactory() {
335 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
336 >        Runnable r = new Runnable() {
337 >                public void run() {
338 >                    try {
339 >                        Thread current = Thread.currentThread();
340 >                        threadAssertTrue(!current.isDaemon());
341 >                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
342 >                        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 >                }
354 >            };
355 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
356 >        
357 >        e.execute(r);
358          try {
359 <            TrackedShortRunnable task = new TrackedShortRunnable();
360 <            assertFalse(task.done);
363 <            Future<String> future = Executors.execute(null, task, TEST_STRING);
364 <            shouldThrow();
365 <        }
366 <        catch (NullPointerException success) {
359 >            e.shutdown();
360 >        } catch(SecurityException ok) {
361          }
362 <        catch (Exception ex) {
362 >        
363 >        try {
364 >            Thread.sleep(SHORT_DELAY_MS);
365 >        } catch (Exception eX) {
366              unexpectedException();
367 +        } finally {
368 +            joinPool(e);
369          }
370      }
371  
372      /**
373 <     * execute with a null runnable throws NPE
373 >     * ThreadPoolExecutor using privilegedThreadFactory has
374 >     * specified group, priority, daemon status, name,
375 >     * access control context and context class loader
376       */
377 <    public void testExecuteNullRunnable() {
377 >    public void testPrivilegedThreadFactory() {
378 >        Policy savedPolicy = null;
379          try {
380 <            Executor e = new DirectExecutor();
381 <            TrackedShortRunnable task = null;
382 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
383 <            shouldThrow();
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 <        catch (NullPointerException success) {
388 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
389 >        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
390 >        final AccessControlContext thisacc = AccessController.getContext();
391 >        Runnable r = new Runnable() {
392 >                public void run() {
393 >                    try {
394 >                        Thread current = Thread.currentThread();
395 >                        threadAssertTrue(!current.isDaemon());
396 >                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
397 >                        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 >                }
411 >            };
412 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
413 >        
414 >        Policy.setPolicy(savedPolicy);
415 >        e.execute(r);
416 >        try {
417 >            e.shutdown();
418 >        } catch(SecurityException ok) {
419          }
420 <        catch (Exception ex) {
420 >        try {
421 >            Thread.sleep(SHORT_DELAY_MS);
422 >        } catch (Exception ex) {
423              unexpectedException();
424 +        } finally {
425 +            joinPool(e);
426          }
427 +
428      }
429  
430 <    /**
431 <     * invoke of a null runnable throws NPE
432 <     */
433 <    public void testInvokeNullRunnable() {
434 <        try {
395 <            Executor e = new DirectExecutor();
396 <            TrackedShortRunnable task = null;
397 <            Executors.invoke(e, task);
398 <            shouldThrow();
399 <        }
400 <        catch (NullPointerException success) {
430 >    void checkCCL() {
431 >        SecurityManager sm = System.getSecurityManager();
432 >        if (sm != null) {
433 >            sm.checkPermission(new RuntimePermission("setContextClassLoader"));
434 >            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
435          }
436 <        catch (Exception ex) {
437 <            unexpectedException();
436 >    }
437 >
438 >    class CheckCCL implements Callable<Object> {
439 >        public Object call() {
440 >            checkCCL();
441 >            return null;
442          }
443      }
444  
445 +
446      /**
447 <     * execute of a null callable throws NPE
447 >     * Without class loader permissions, creating
448 >     * privilegedCallableUsingCurrentClassLoader throws ACE
449       */
450 <    public void testExecuteNullCallable() {
450 >    public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
451 >        Policy savedPolicy = null;
452          try {
453 <            Executor e = new DirectExecutor();
454 <            StringTask t = null;
455 <            Future<String> future = Executors.execute(e, t);
456 <            shouldThrow();
457 <        }
417 <        catch (NullPointerException success) {
453 >            savedPolicy = Policy.getPolicy();
454 >            AdjustablePolicy policy = new AdjustablePolicy();
455 >            Policy.setPolicy(policy);
456 >        } catch (AccessControlException ok) {
457 >            return;
458          }
459 <        catch (Exception ex) {
459 >
460 >        // 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 >        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 <     * invoke of a null callable throws NPE
482 >     * With class loader permissions, calling
483 >     * privilegedCallableUsingCurrentClassLoader does not throw ACE
484       */
485 <    public void testInvokeNullCallable() {
485 >    public void testprivilegedCallableUsingCCLWithPrivs() {
486 >        Policy savedPolicy = null;
487          try {
488 <            Executor e = new DirectExecutor();
489 <            StringTask t = null;
490 <            String result = Executors.invoke(e, t);
491 <            shouldThrow();
492 <        }
493 <        catch (NullPointerException success) {
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 <        catch (Exception ex) {
496 >            
497 >        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 <     *  execute(Executor, Runnable) throws RejectedExecutionException
443 <     *  if saturated.
509 >     * Without permissions, calling privilegedCallable throws ACE
510       */
511 <    public void testExecute1() {
512 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
511 >    public void testprivilegedCallableWithNoPrivs() {
512 >        Callable task;
513 >        Policy savedPolicy = null;
514 >        AdjustablePolicy policy = null;
515 >        AccessControlContext noprivAcc = null;
516          try {
517 <            
518 <            for(int i = 0; i < 5; ++i){
519 <                Executors.execute(p, new MediumRunnable(), Boolean.TRUE);
520 <            }
517 >            savedPolicy = Policy.getPolicy();
518 >            policy = new AdjustablePolicy();
519 >            Policy.setPolicy(policy);
520 >            noprivAcc = AccessController.getContext();
521 >            task = Executors.privilegedCallable(new CheckCCL());
522 >            Policy.setPolicy(savedPolicy);
523 >        } catch (AccessControlException ok) {
524 >            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 >            return;
536 >        } catch(AccessControlException ok) {
537 >        }
538 >
539 >        try {
540 >            task.call();
541              shouldThrow();
542 <        } catch(RejectedExecutionException success){}
543 <        joinPool(p);
542 >        } catch(AccessControlException success) {
543 >        } catch(Exception ex) {
544 >            unexpectedException();
545 >        }
546      }
547  
548      /**
549 <     *  execute(Executor, Callable)throws RejectedExecutionException
459 <     *  if saturated.
549 >     * With permissions, calling privilegedCallable succeeds
550       */
551 <    public void testExecute2() {
552 <         ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
551 >    public void testprivilegedCallableWithPrivs() {
552 >        Policy savedPolicy = null;
553          try {
554 <            for(int i = 0; i < 5; ++i) {
555 <                Executors.execute(p, new SmallCallable());
556 <            }
557 <            shouldThrow();
558 <        } catch(RejectedExecutionException e){}
559 <        joinPool(p);
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 >        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  
472
573      /**
574 <     *  invoke(Executor, Runnable) throws InterruptedException if
575 <     *  caller interrupted.
576 <     */
477 <    public void testInterruptedInvoke() {
478 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
479 <        Thread t = new Thread(new Runnable() {
480 <                public void run() {
481 <                    try {
482 <                        Executors.invoke(p,new Runnable() {
483 <                                public void run() {
484 <                                    try {
485 <                                        Thread.sleep(MEDIUM_DELAY_MS);
486 <                                        shouldThrow();
487 <                                    } catch(InterruptedException e){
488 <                                    }
489 <                                }
490 <                            });
491 <                    } catch(InterruptedException success){
492 <                    } catch(Exception e) {
493 <                        unexpectedException();
494 <                    }
495 <                    
496 <                }
497 <            });
574 >     * callable(Runnable) returns null when called
575 >     */
576 >    public void testCallable1() {
577          try {
578 <            t.start();
579 <            Thread.sleep(SHORT_DELAY_MS);
580 <            t.interrupt();
502 <        } catch(Exception e){
578 >            Callable c = Executors.callable(new NoOpRunnable());
579 >            assertNull(c.call());
580 >        } catch(Exception ex) {
581              unexpectedException();
582          }
583 <        joinPool(p);
583 >        
584      }
585  
586      /**
587 <     *  invoke(Executor, Runnable) throws ExecutionException if
588 <     *  runnable throws exception.
589 <     */
512 <    public void testInvoke3() {
513 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
587 >     * callable(Runnable, result) returns result when called
588 >     */
589 >    public void testCallable2() {
590          try {
591 <            Runnable r = new Runnable() {
592 <                    public void run() {
593 <                        int i = 5/0;
518 <                    }
519 <                };
520 <            
521 <            for(int i =0; i < 5; i++){
522 <                Executors.invoke(p,r);
523 <            }
524 <            
525 <            shouldThrow();
526 <        } catch(ExecutionException success){
527 <        } catch(Exception e){
591 >            Callable c = Executors.callable(new NoOpRunnable(), one);
592 >            assertEquals(one, c.call());
593 >        } catch(Exception ex) {
594              unexpectedException();
595          }
530        joinPool(p);
596      }
597  
533
534
598      /**
599 <     *  invoke(Executor, Callable) throws InterruptedException if
600 <     *  callable throws exception
601 <     */
539 <    public void testInvoke5() {
540 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
541 <        
542 <        final Callable c = new Callable() {
543 <                public Object call() {
544 <                    try {
545 <                        Executors.invoke(p, new SmallCallable());
546 <                        shouldThrow();
547 <                    } catch(InterruptedException e){}
548 <                    catch(RejectedExecutionException e2){}
549 <                    catch(ExecutionException e3){}
550 <                    return Boolean.TRUE;
551 <                }
552 <            };
553 <
554 <
555 <        
556 <        Thread t = new Thread(new Runnable() {
557 <                public void run() {
558 <                    try {
559 <                        c.call();
560 <                    } catch(Exception e){}
561 <                }
562 <          });
599 >     * callable(PrivilegedAction) returns its result when called
600 >     */
601 >    public void testCallable3() {
602          try {
603 <            t.start();
604 <            Thread.sleep(SHORT_DELAY_MS);
605 <            t.interrupt();
606 <            t.join();
568 <        } catch(InterruptedException e){
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          }
571        
572        joinPool(p);
609      }
610  
611      /**
612 <     *  invoke(Executor, Callable) will throw ExecutionException
613 <     *  if callable throws exception
614 <     */
579 <    public void testInvoke6() {
580 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
581 <
612 >     * callable(PrivilegedExceptionAction) returns its result when called
613 >     */
614 >    public void testCallable4() {
615          try {
616 <            Callable c = new Callable() {
617 <                    public Object call() {
618 <                        int i = 5/0;
619 <                        return Boolean.TRUE;
587 <                    }
588 <                };
589 <            
590 <            for(int i =0; i < 5; i++){
591 <                Executors.invoke(p,c);
592 <            }
593 <            
594 <            shouldThrow();
595 <        }
596 <        catch(ExecutionException success){
597 <        } catch(Exception e) {
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          }
600        joinPool(p);
622      }
623  
624  
604
625      /**
626 <     *  timeouts from execute will time out if they compute too long.
627 <     */
628 <    public void testTimedCallable() {
609 <        int N = 10000;
610 <        ExecutorService executor = Executors.newSingleThreadExecutor();
611 <        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
626 >     * callable(null Runnable) throws NPE
627 >     */
628 >    public void testCallableNPE1() {
629          try {
630 <            long startTime = System.currentTimeMillis();
631 <            
632 <            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 <                    unexpectedException();
634 <                }
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 <            joinPool(executor);
630 >            Runnable r = null;
631 >            Callable c = Executors.callable(r);
632 >        } catch (NullPointerException success) {
633          }
634      }
635  
645    
636      /**
637 <     * ThreadPoolExecutor using defaultThreadFactory has
638 <     * specified group, priority, daemon status, and name
639 <     */
640 <    public void testDefaultThreadFactory() {
641 <        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
642 <        Runnable r = new Runnable() {
643 <                public void run() {
644 <                    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 <        }
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 <     * ThreadPoolExecutor using privilegedThreadFactory has
649 <     * specified group, priority, daemon status, name,
650 <     * access control context and context class loader
651 <     */
652 <    public void testPrivilegedThreadFactory() {
653 <        Policy savedPolicy = Policy.getPolicy();
654 <        AdjustablePolicy policy = new AdjustablePolicy();
655 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
656 <        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 <        }
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 +
670   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines