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.23 by jsr166, Thu Nov 19 03:55:29 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 12 | Line 13 | import java.util.concurrent.*;
13   import java.math.BigInteger;
14   import java.security.*;
15  
16 < public class ExecutorsTest extends JSR166TestCase{
16 > public class ExecutorsTest extends JSR166TestCase {
17      public static void main(String[] args) {
18 <        junit.textui.TestRunner.run (suite());  
18 >        junit.textui.TestRunner.run (suite());
19      }
20      public static Test suite() {
21 <        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 <        }
21 >        return new TestSuite(ExecutorsTest.class);
22      }
23  
24      static class TimedCallable<T> implements Callable<T> {
25 <        private final Executor exec;
25 >        private final ExecutorService exec;
26          private final Callable<T> func;
27          private final long msecs;
28 <        
29 <        TimedCallable(Executor exec, Callable<T> func, long msecs) {
28 >
29 >        TimedCallable(ExecutorService exec, Callable<T> func, long msecs) {
30              this.exec = exec;
31              this.func = func;
32              this.msecs = msecs;
33          }
34 <        
34 >
35          public T call() throws Exception {
36 <            Future<T> ftask = Executors.execute(exec, func);
36 >            Future<T> ftask = exec.submit(func);
37              try {
38                  return ftask.get(msecs, TimeUnit.MILLISECONDS);
39              } finally {
# Line 80 | Line 69 | public class ExecutorsTest extends JSR16
69          e.execute(new NoOpRunnable());
70          e.execute(new NoOpRunnable());
71          e.execute(new NoOpRunnable());
72 <        e.shutdown();
72 >        joinPool(e);
73      }
74  
75      /**
# Line 91 | Line 80 | public class ExecutorsTest extends JSR16
80          e.execute(new NoOpRunnable());
81          e.execute(new NoOpRunnable());
82          e.execute(new NoOpRunnable());
83 <        e.shutdown();
83 >        joinPool(e);
84      }
85  
86      /**
# Line 101 | Line 90 | public class ExecutorsTest extends JSR16
90          try {
91              ExecutorService e = Executors.newCachedThreadPool(null);
92              shouldThrow();
93 <        }
105 <        catch(NullPointerException success) {
106 <        }
93 >        } catch (NullPointerException success) {}
94      }
95  
96  
# Line 115 | Line 102 | public class ExecutorsTest extends JSR16
102          e.execute(new NoOpRunnable());
103          e.execute(new NoOpRunnable());
104          e.execute(new NoOpRunnable());
105 <        e.shutdown();
105 >        joinPool(e);
106      }
107  
108      /**
# Line 126 | Line 113 | public class ExecutorsTest extends JSR16
113          e.execute(new NoOpRunnable());
114          e.execute(new NoOpRunnable());
115          e.execute(new NoOpRunnable());
116 <        e.shutdown();
116 >        joinPool(e);
117      }
118  
119      /**
# Line 136 | Line 123 | public class ExecutorsTest extends JSR16
123          try {
124              ExecutorService e = Executors.newSingleThreadExecutor(null);
125              shouldThrow();
126 <        }
127 <        catch(NullPointerException success) {
126 >        } catch (NullPointerException success) {}
127 >    }
128 >
129 >    /**
130 >     * A new SingleThreadExecutor cannot be casted to concrete implementation
131 >     */
132 >    public void testCastNewSingleThreadExecutor() {
133 >        ExecutorService e = Executors.newSingleThreadExecutor();
134 >        try {
135 >            ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
136 >            shouldThrow();
137 >        } catch (ClassCastException success) {
138 >        } finally {
139 >            joinPool(e);
140          }
141      }
142  
143 +
144      /**
145       * A new newFixedThreadPool can execute runnables
146       */
# Line 149 | Line 149 | public class ExecutorsTest extends JSR16
149          e.execute(new NoOpRunnable());
150          e.execute(new NoOpRunnable());
151          e.execute(new NoOpRunnable());
152 <        e.shutdown();
152 >        joinPool(e);
153      }
154  
155      /**
# Line 160 | Line 160 | public class ExecutorsTest extends JSR16
160          e.execute(new NoOpRunnable());
161          e.execute(new NoOpRunnable());
162          e.execute(new NoOpRunnable());
163 <        e.shutdown();
163 >        joinPool(e);
164      }
165  
166      /**
# Line 170 | Line 170 | public class ExecutorsTest extends JSR16
170          try {
171              ExecutorService e = Executors.newFixedThreadPool(2, null);
172              shouldThrow();
173 <        }
174 <        catch(NullPointerException success) {
175 <        }
173 >        } catch (NullPointerException success) {}
174      }
175  
176      /**
# Line 182 | Line 180 | public class ExecutorsTest extends JSR16
180          try {
181              ExecutorService e = Executors.newFixedThreadPool(0);
182              shouldThrow();
183 <        }
186 <        catch(IllegalArgumentException success) {
187 <        }
183 >        } catch (IllegalArgumentException success) {}
184      }
185  
186 +
187      /**
188 <     * execute of runnable runs it to completion
188 >     * An unconfigurable newFixedThreadPool can execute runnables
189       */
190 <    public void testExecuteRunnable() {
191 <        try {
192 <            Executor e = new DirectExecutor();
193 <            TrackedShortRunnable task = new TrackedShortRunnable();
194 <            assertFalse(task.done);
195 <            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 <        }
190 >    public void testunconfigurableExecutorService() {
191 >        ExecutorService e = Executors.unconfigurableExecutorService(Executors.newFixedThreadPool(2));
192 >        e.execute(new NoOpRunnable());
193 >        e.execute(new NoOpRunnable());
194 >        e.execute(new NoOpRunnable());
195 >        joinPool(e);
196      }
197  
198      /**
199 <     * invoke of a runnable runs it to completion
199 >     * unconfigurableExecutorService(null) throws NPE
200       */
201 <    public void testInvokeRunnable() {
201 >    public void testunconfigurableExecutorServiceNPE() {
202          try {
203 <            Executor e = new DirectExecutor();
204 <            TrackedShortRunnable task = new TrackedShortRunnable();
205 <            assertFalse(task.done);
219 <            Executors.invoke(e, task);
220 <            assertTrue(task.done);
221 <        }
222 <        catch (ExecutionException ex) {
223 <            unexpectedException();
224 <        }
225 <        catch (InterruptedException ex) {
226 <            unexpectedException();
227 <        }
203 >            ExecutorService e = Executors.unconfigurableExecutorService(null);
204 >            shouldThrow();
205 >        } catch (NullPointerException success) {}
206      }
207  
208      /**
209 <     * execute of a callable runs it to completion
209 >     * unconfigurableScheduledExecutorService(null) throws NPE
210       */
211 <    public void testExecuteCallable() {
211 >    public void testunconfigurableScheduledExecutorServiceNPE() {
212          try {
213 <            Executor e = new DirectExecutor();
214 <            Future<String> future = Executors.execute(e, new StringTask());
215 <            String result = future.get();
238 <            assertSame(TEST_STRING, result);
239 <        }
240 <        catch (ExecutionException ex) {
241 <            unexpectedException();
242 <        }
243 <        catch (InterruptedException ex) {
244 <            unexpectedException();
245 <        }
213 >            ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
214 >            shouldThrow();
215 >        } catch (NullPointerException success) {}
216      }
217  
218  
219      /**
220 <     * execute of a privileged action runs it to completion
220 >     * a newSingleThreadScheduledExecutor successfully runs delayed task
221       */
222 <    public void testExecutePrivilegedAction() {
223 <        Policy savedPolicy = Policy.getPolicy();
224 <        AdjustablePolicy policy = new AdjustablePolicy();
225 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
226 <        policy.addPermission(new RuntimePermission("setContextClassLoader"));
227 <        Policy.setPolicy(policy);
228 <        try {
229 <            Executor e = new DirectExecutor();
230 <            Future future = Executors.execute(e, new PrivilegedAction() {
231 <                    public Object run() {
232 <                        return TEST_STRING;
263 <                    }});
264 <
265 <            Object result = future.get();
266 <            assertSame(TEST_STRING, result);
267 <        }
268 <        catch (ExecutionException ex) {
269 <            unexpectedException();
270 <        }
271 <        catch (InterruptedException ex) {
272 <            unexpectedException();
273 <        }
274 <        finally {
275 <            Policy.setPolicy(savedPolicy);
276 <        }
222 >    public void testNewSingleThreadScheduledExecutor() throws Exception {
223 >        try {
224 >            TrackedCallable callable = new TrackedCallable();
225 >            ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
226 >            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
227 >            assertFalse(callable.done);
228 >            Thread.sleep(MEDIUM_DELAY_MS);
229 >            assertTrue(callable.done);
230 >            assertEquals(Boolean.TRUE, f.get());
231 >            joinPool(p1);
232 >        } catch (RejectedExecutionException e) {}
233      }
234  
235      /**
236 <     * execute of a privileged exception action runs it to completion
236 >     * a newScheduledThreadPool successfully runs delayed task
237       */
238 <    public void testExecutePrivilegedExceptionAction() {
239 <        Policy savedPolicy = Policy.getPolicy();
240 <        AdjustablePolicy policy = new AdjustablePolicy();
241 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
242 <        policy.addPermission(new RuntimePermission("setContextClassLoader"));
243 <        Policy.setPolicy(policy);
244 <        try {
245 <            Executor e = new DirectExecutor();
246 <            Future future = Executors.execute(e, new PrivilegedExceptionAction() {
247 <                    public Object run() {
248 <                        return TEST_STRING;
249 <                    }});
238 >    public void testnewScheduledThreadPool() throws Exception {
239 >        try {
240 >            TrackedCallable callable = new TrackedCallable();
241 >            ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
242 >            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
243 >            assertFalse(callable.done);
244 >            Thread.sleep(MEDIUM_DELAY_MS);
245 >            assertTrue(callable.done);
246 >            assertEquals(Boolean.TRUE, f.get());
247 >            joinPool(p1);
248 >        } catch (RejectedExecutionException e) {}
249 >    }
250  
251 <            Object result = future.get();
252 <            assertSame(TEST_STRING, result);
253 <        }
254 <        catch (ExecutionException ex) {
255 <            unexpectedException();
256 <        }
257 <        catch (InterruptedException ex) {
258 <            unexpectedException();
259 <        }
260 <        finally {
261 <            Policy.setPolicy(savedPolicy);
262 <        }
251 >    /**
252 >     * an unconfigurable  newScheduledThreadPool successfully runs delayed task
253 >     */
254 >    public void testunconfigurableScheduledExecutorService() throws Exception {
255 >        try {
256 >            TrackedCallable callable = new TrackedCallable();
257 >            ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
258 >            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
259 >            assertFalse(callable.done);
260 >            Thread.sleep(MEDIUM_DELAY_MS);
261 >            assertTrue(callable.done);
262 >            assertEquals(Boolean.TRUE, f.get());
263 >            joinPool(p1);
264 >        } catch (RejectedExecutionException e) {}
265      }
266  
267      /**
268 <     * execute of a failed privileged exception action reports exception
268 >     *  timeouts from execute will time out if they compute too long.
269       */
270 <    public void testExecuteFailedPrivilegedExceptionAction() {
271 <        Policy savedPolicy = Policy.getPolicy();
272 <        AdjustablePolicy policy = new AdjustablePolicy();
273 <        policy.addPermission(new RuntimePermission("getContextClassLoader"));
316 <        policy.addPermission(new RuntimePermission("setContextClassLoader"));
317 <        Policy.setPolicy(policy);
270 >    public void testTimedCallable() throws Exception {
271 >        int N = 10000;
272 >        ExecutorService executor = Executors.newSingleThreadExecutor();
273 >        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
274          try {
275 <            Executor e = new DirectExecutor();
320 <            Future future = Executors.execute(e, new PrivilegedExceptionAction() {
321 <                    public Object run() throws Exception {
322 <                        throw new IndexOutOfBoundsException();
323 <                    }});
275 >            long startTime = System.currentTimeMillis();
276  
277 <            Object result = future.get();
278 <            shouldThrow();
279 <        }
280 <        catch (ExecutionException success) {
277 >            long i = 0;
278 >            while (tasks.size() < N) {
279 >                tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
280 >                i += 10;
281 >            }
282 >
283 >            int iters = 0;
284 >            BigInteger sum = BigInteger.ZERO;
285 >            for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
286 >                try {
287 >                    ++iters;
288 >                    sum = sum.add(it.next().call());
289 >                }
290 >                catch (TimeoutException success) {
291 >                    assertTrue(iters > 0);
292 >                    return;
293 >                }
294 >            }
295 >            // if by chance we didn't ever time out, total time must be small
296 >            long elapsed = System.currentTimeMillis() - startTime;
297 >            assertTrue(elapsed < N);
298          }
299 <        catch (InterruptedException ex) {
300 <            unexpectedException();
299 >        finally {
300 >            joinPool(executor);
301          }
333        finally {
334            Policy.setPolicy(savedPolicy);
335        }
302      }
303  
304 +
305      /**
306 <     * invoke of a collable runs it to completion
306 >     * ThreadPoolExecutor using defaultThreadFactory has
307 >     * specified group, priority, daemon status, and name
308       */
309 <    public void testInvokeCallable() {
310 <        try {
311 <            Executor e = new DirectExecutor();
312 <            String result = Executors.invoke(e, new StringTask());
309 >    public void testDefaultThreadFactory() throws Exception {
310 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
311 >        Runnable r = new Runnable() {
312 >                public void run() {
313 >                    try {
314 >                        Thread current = Thread.currentThread();
315 >                        threadAssertTrue(!current.isDaemon());
316 >                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
317 >                        ThreadGroup g = current.getThreadGroup();
318 >                        SecurityManager s = System.getSecurityManager();
319 >                        if (s != null)
320 >                            threadAssertTrue(g == s.getThreadGroup());
321 >                        else
322 >                            threadAssertTrue(g == egroup);
323 >                        String name = current.getName();
324 >                        threadAssertTrue(name.endsWith("thread-1"));
325 >                    } catch (SecurityException ok) {
326 >                        // Also pass if not allowed to change setting
327 >                    }
328 >                }
329 >            };
330 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
331  
332 <            assertSame(TEST_STRING, result);
333 <        }
334 <        catch (ExecutionException ex) {
335 <            unexpectedException();
332 >        e.execute(r);
333 >        try {
334 >            e.shutdown();
335 >        } catch (SecurityException ok) {
336          }
337 <        catch (InterruptedException ex) {
338 <            unexpectedException();
337 >
338 >        try {
339 >            Thread.sleep(SHORT_DELAY_MS);
340 >        } finally {
341 >            joinPool(e);
342          }
343      }
344  
345      /**
346 <     * execute with null executor throws NPE
346 >     * ThreadPoolExecutor using privilegedThreadFactory has
347 >     * specified group, priority, daemon status, name,
348 >     * access control context and context class loader
349       */
350 <    public void testNullExecuteRunnable() {
350 >    public void testPrivilegedThreadFactory() throws Exception {
351 >        Policy savedPolicy = null;
352          try {
353 <            TrackedShortRunnable task = new TrackedShortRunnable();
354 <            assertFalse(task.done);
355 <            Future<String> future = Executors.execute(null, task, TEST_STRING);
356 <            shouldThrow();
353 >            savedPolicy = Policy.getPolicy();
354 >            AdjustablePolicy policy = new AdjustablePolicy();
355 >            policy.addPermission(new RuntimePermission("getContextClassLoader"));
356 >            policy.addPermission(new RuntimePermission("setContextClassLoader"));
357 >            Policy.setPolicy(policy);
358 >        } catch (AccessControlException ok) {
359 >            return;
360          }
361 <        catch (NullPointerException success) {
361 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
362 >        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
363 >        final AccessControlContext thisacc = AccessController.getContext();
364 >        Runnable r = new Runnable() {
365 >                public void run() {
366 >                    try {
367 >                        Thread current = Thread.currentThread();
368 >                        threadAssertTrue(!current.isDaemon());
369 >                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
370 >                        ThreadGroup g = current.getThreadGroup();
371 >                        SecurityManager s = System.getSecurityManager();
372 >                        if (s != null)
373 >                            threadAssertTrue(g == s.getThreadGroup());
374 >                        else
375 >                            threadAssertTrue(g == egroup);
376 >                        String name = current.getName();
377 >                        threadAssertTrue(name.endsWith("thread-1"));
378 >                        threadAssertTrue(thisccl == current.getContextClassLoader());
379 >                        threadAssertTrue(thisacc.equals(AccessController.getContext()));
380 >                    } catch (SecurityException ok) {
381 >                        // Also pass if not allowed to change settings
382 >                    }
383 >                }
384 >            };
385 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
386 >
387 >        Policy.setPolicy(savedPolicy);
388 >        e.execute(r);
389 >        try {
390 >            e.shutdown();
391 >        } catch (SecurityException ok) {
392          }
393 <        catch (Exception ex) {
394 <            unexpectedException();
393 >        try {
394 >            Thread.sleep(SHORT_DELAY_MS);
395 >        } finally {
396 >            joinPool(e);
397 >        }
398 >
399 >    }
400 >
401 >    void checkCCL() {
402 >        SecurityManager sm = System.getSecurityManager();
403 >        if (sm != null) {
404 >            sm.checkPermission(new RuntimePermission("setContextClassLoader"));
405 >            sm.checkPermission(new RuntimePermission("getClassLoader"));
406 >        }
407 >    }
408 >
409 >    class CheckCCL implements Callable<Object> {
410 >        public Object call() {
411 >            checkCCL();
412 >            return null;
413          }
414      }
415  
416 +
417      /**
418 <     * execute with a null runnable throws NPE
418 >     * Without class loader permissions, creating
419 >     * privilegedCallableUsingCurrentClassLoader throws ACE
420       */
421 <    public void testExecuteNullRunnable() {
421 >    public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
422 >        Policy savedPolicy = null;
423          try {
424 <            Executor e = new DirectExecutor();
425 <            TrackedShortRunnable task = null;
426 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
427 <            shouldThrow();
424 >            savedPolicy = Policy.getPolicy();
425 >            AdjustablePolicy policy = new AdjustablePolicy();
426 >            Policy.setPolicy(policy);
427 >        } catch (AccessControlException ok) {
428 >            return;
429          }
430 <        catch (NullPointerException success) {
430 >
431 >        // Check if program still has too many permissions to run test
432 >        try {
433 >            checkCCL();
434 >            // too many privileges to test; so return
435 >            Policy.setPolicy(savedPolicy);
436 >            return;
437 >        } catch (AccessControlException ok) {
438          }
439 <        catch (Exception ex) {
440 <            unexpectedException();
439 >
440 >        try {
441 >            Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
442 >            shouldThrow();
443 >        } catch (AccessControlException success) {
444 >        } finally {
445 >            Policy.setPolicy(savedPolicy);
446          }
447      }
448  
449      /**
450 <     * invoke of a null runnable throws NPE
450 >     * With class loader permissions, calling
451 >     * privilegedCallableUsingCurrentClassLoader does not throw ACE
452       */
453 <    public void testInvokeNullRunnable() {
453 >    public void testprivilegedCallableUsingCCLWithPrivs() throws Exception {
454 >        Policy savedPolicy = null;
455          try {
456 <            Executor e = new DirectExecutor();
457 <            TrackedShortRunnable task = null;
458 <            Executors.invoke(e, task);
459 <            shouldThrow();
456 >            savedPolicy = Policy.getPolicy();
457 >            AdjustablePolicy policy = new AdjustablePolicy();
458 >            policy.addPermission(new RuntimePermission("getContextClassLoader"));
459 >            policy.addPermission(new RuntimePermission("setContextClassLoader"));
460 >            Policy.setPolicy(policy);
461 >        } catch (AccessControlException ok) {
462 >            return;
463          }
464 <        catch (NullPointerException success) {
464 >
465 >        try {
466 >            Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
467 >            task.call();
468          }
469 <        catch (Exception ex) {
470 <            unexpectedException();
469 >        finally {
470 >            Policy.setPolicy(savedPolicy);
471          }
472      }
473  
474      /**
475 <     * execute of a null callable throws NPE
475 >     * Without permissions, calling privilegedCallable throws ACE
476       */
477 <    public void testExecuteNullCallable() {
477 >    public void testprivilegedCallableWithNoPrivs() throws Exception {
478 >        Callable task;
479 >        Policy savedPolicy = null;
480 >        AdjustablePolicy policy = null;
481 >        AccessControlContext noprivAcc = null;
482          try {
483 <            Executor e = new DirectExecutor();
484 <            StringTask t = null;
485 <            Future<String> future = Executors.execute(e, t);
486 <            shouldThrow();
487 <        }
488 <        catch (NullPointerException success) {
483 >            savedPolicy = Policy.getPolicy();
484 >            policy = new AdjustablePolicy();
485 >            Policy.setPolicy(policy);
486 >            noprivAcc = AccessController.getContext();
487 >            task = Executors.privilegedCallable(new CheckCCL());
488 >            Policy.setPolicy(savedPolicy);
489 >        } catch (AccessControlException ok) {
490 >            return; // program has too few permissions to set up test
491          }
492 <        catch (Exception ex) {
493 <            unexpectedException();
492 >
493 >        // Make sure that program doesn't have too many permissions
494 >        try {
495 >            AccessController.doPrivileged(new PrivilegedAction() {
496 >                    public Object run() {
497 >                        checkCCL();
498 >                        return null;
499 >                    }}, noprivAcc);
500 >            // too many permssions; skip test
501 >            return;
502 >        } catch (AccessControlException ok) {
503          }
504 +
505 +        try {
506 +            task.call();
507 +            shouldThrow();
508 +        } catch (AccessControlException success) {}
509      }
510  
511      /**
512 <     * invoke of a null callable throws NPE
512 >     * With permissions, calling privilegedCallable succeeds
513       */
514 <    public void testInvokeNullCallable() {
514 >    public void testprivilegedCallableWithPrivs() throws Exception {
515 >        Policy savedPolicy = null;
516          try {
517 <            Executor e = new DirectExecutor();
518 <            StringTask t = null;
519 <            String result = Executors.invoke(e, t);
520 <            shouldThrow();
517 >            savedPolicy = Policy.getPolicy();
518 >            AdjustablePolicy policy = new AdjustablePolicy();
519 >            policy.addPermission(new RuntimePermission("getContextClassLoader"));
520 >            policy.addPermission(new RuntimePermission("setContextClassLoader"));
521 >            Policy.setPolicy(policy);
522 >        } catch (AccessControlException ok) {
523 >            return;
524          }
525 <        catch (NullPointerException success) {
526 <        }
527 <        catch (Exception ex) {
528 <            unexpectedException();
525 >
526 >        Callable task = Executors.privilegedCallable(new CheckCCL());
527 >        try {
528 >            task.call();
529 >        } finally {
530 >            Policy.setPolicy(savedPolicy);
531          }
532      }
533  
534      /**
535 <     *  execute(Executor, Runnable) throws RejectedExecutionException
443 <     *  if saturated.
535 >     * callable(Runnable) returns null when called
536       */
537 <    public void testExecute1() {
538 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
539 <        try {
448 <            
449 <            for(int i = 0; i < 5; ++i){
450 <                Executors.execute(p, new MediumRunnable(), Boolean.TRUE);
451 <            }
452 <            shouldThrow();
453 <        } catch(RejectedExecutionException success){}
454 <        joinPool(p);
537 >    public void testCallable1() throws Exception {
538 >        Callable c = Executors.callable(new NoOpRunnable());
539 >        assertNull(c.call());
540      }
541  
542      /**
543 <     *  execute(Executor, Callable)throws RejectedExecutionException
459 <     *  if saturated.
543 >     * callable(Runnable, result) returns result when called
544       */
545 <    public void testExecute2() {
546 <         ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
547 <        try {
464 <            for(int i = 0; i < 5; ++i) {
465 <                Executors.execute(p, new SmallCallable());
466 <            }
467 <            shouldThrow();
468 <        } catch(RejectedExecutionException e){}
469 <        joinPool(p);
545 >    public void testCallable2() throws Exception {
546 >        Callable c = Executors.callable(new NoOpRunnable(), one);
547 >        assertEquals(one, c.call());
548      }
549  
472
550      /**
551 <     *  invoke(Executor, Runnable) throws InterruptedException if
475 <     *  caller interrupted.
551 >     * callable(PrivilegedAction) returns its result when called
552       */
553 <    public void testInterruptedInvoke() {
554 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
555 <        Thread t = new Thread(new Runnable() {
556 <                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 <            });
498 <        try {
499 <            t.start();
500 <            Thread.sleep(SHORT_DELAY_MS);
501 <            t.interrupt();
502 <        } catch(Exception e){
503 <            unexpectedException();
504 <        }
505 <        joinPool(p);
553 >    public void testCallable3() throws Exception {
554 >        Callable c = Executors.callable(new PrivilegedAction() {
555 >                public Object run() { return one; }});
556 >        assertEquals(one, c.call());
557      }
558  
559      /**
560 <     *  invoke(Executor, Runnable) throws ExecutionException if
510 <     *  runnable throws exception.
560 >     * callable(PrivilegedExceptionAction) returns its result when called
561       */
562 <    public void testInvoke3() {
563 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
564 <        try {
565 <            Runnable r = new Runnable() {
516 <                    public void run() {
517 <                        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){
528 <            unexpectedException();
529 <        }
530 <        joinPool(p);
562 >    public void testCallable4() throws Exception {
563 >        Callable c = Executors.callable(new PrivilegedExceptionAction() {
564 >                public Object run() { return one; }});
565 >        assertEquals(one, c.call());
566      }
567  
568  
534
569      /**
570 <     *  invoke(Executor, Callable) throws InterruptedException if
537 <     *  callable throws exception
570 >     * callable(null Runnable) throws NPE
571       */
572 <    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 <          });
572 >    public void testCallableNPE1() {
573          try {
574 <            t.start();
575 <            Thread.sleep(SHORT_DELAY_MS);
576 <            t.interrupt();
567 <            t.join();
568 <        } catch(InterruptedException e){
569 <            unexpectedException();
570 <        }
571 <        
572 <        joinPool(p);
574 >            Callable c = Executors.callable((Runnable) null);
575 >            shouldThrow();
576 >        } catch (NullPointerException success) {}
577      }
578  
579      /**
580 <     *  invoke(Executor, Callable) will throw ExecutionException
577 <     *  if callable throws exception
580 >     * callable(null, result) throws NPE
581       */
582 <    public void testInvoke6() {
580 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
581 <
582 >    public void testCallableNPE2() {
583          try {
584 <            Callable c = new Callable() {
584 <                    public Object call() {
585 <                        int i = 5/0;
586 <                        return Boolean.TRUE;
587 <                    }
588 <                };
589 <            
590 <            for(int i =0; i < 5; i++){
591 <                Executors.invoke(p,c);
592 <            }
593 <            
584 >            Callable c = Executors.callable((Runnable) null, one);
585              shouldThrow();
586 <        }
596 <        catch(ExecutionException success){
597 <        } catch(Exception e) {
598 <            unexpectedException();
599 <        }
600 <        joinPool(p);
586 >        } catch (NullPointerException success) {}
587      }
588  
603
604
589      /**
590 <     *  timeouts from execute will time out if they compute too long.
590 >     * callable(null PrivilegedAction) throws NPE
591       */
592 <    public void testTimedCallable() {
609 <        int N = 10000;
610 <        ExecutorService executor = Executors.newSingleThreadExecutor();
611 <        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
592 >    public void testCallableNPE3() {
593          try {
594 <            long startTime = System.currentTimeMillis();
595 <            
596 <            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);
642 <        }
594 >            Callable c = Executors.callable((PrivilegedAction) null);
595 >            shouldThrow();
596 >        } catch (NullPointerException success) {}
597      }
598  
645    
599      /**
600 <     * ThreadPoolExecutor using defaultThreadFactory has
648 <     * specified group, priority, daemon status, and name
600 >     * callable(null PrivilegedExceptionAction) throws NPE
601       */
602 <    public void testDefaultThreadFactory() {
603 <        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
604 <        Runnable r = new Runnable() {
605 <                public void run() {
606 <                    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 <        }
602 >    public void testCallableNPE4() {
603 >        try {
604 >            Callable c = Executors.callable((PrivilegedExceptionAction) null);
605 >            shouldThrow();
606 >        } catch (NullPointerException success) {}
607      }
608  
680    /**
681     * ThreadPoolExecutor using privilegedThreadFactory has
682     * specified group, priority, daemon status, name,
683     * access control context and context class loader
684     */
685    public void testPrivilegedThreadFactory() {
686        Policy savedPolicy = Policy.getPolicy();
687        AdjustablePolicy policy = new AdjustablePolicy();
688        policy.addPermission(new RuntimePermission("getContextClassLoader"));
689        policy.addPermission(new RuntimePermission("setContextClassLoader"));
690        Policy.setPolicy(policy);
691        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
692        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
693        final AccessControlContext thisacc = AccessController.getContext();
694        Runnable r = new Runnable() {
695                public void run() {
696                    Thread current = Thread.currentThread();
697                    threadAssertTrue(!current.isDaemon());
698                    threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
699                    ThreadGroup g = current.getThreadGroup();
700                    SecurityManager s = System.getSecurityManager();
701                    if (s != null)
702                        threadAssertTrue(g == s.getThreadGroup());
703                    else
704                        threadAssertTrue(g == egroup);
705                    String name = current.getName();
706                    threadAssertTrue(name.endsWith("thread-1"));
707                    threadAssertTrue(thisccl == current.getContextClassLoader());
708                    threadAssertTrue(thisacc.equals(AccessController.getContext()));
709                }
710            };
711        ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
712        
713        Policy.setPolicy(savedPolicy);
714        e.execute(r);
715        e.shutdown();
716        try {
717            Thread.sleep(SHORT_DELAY_MS);
718        } catch (Exception ex) {
719            unexpectedException();
720        } finally {
721            joinPool(e);
722        }
723
724    }
609  
610   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines