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.18 by dl, Tue Aug 4 13:58:09 2009 UTC vs.
Revision 1.41 by jsr166, Sun May 29 06:54:23 2011 UTC

# Line 1 | Line 1
1   /*
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.
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5 > * Other contributors include Andrew Wright, Jeffrey Hayes,
6 > * Pat Fisher, Mike Judd.
7   */
8  
9
9   import junit.framework.*;
10   import java.util.*;
11   import java.util.concurrent.*;
12 < import java.math.BigInteger;
12 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
13   import java.security.*;
15 import sun.security.util.SecurityConstants;
14  
15 < public class ExecutorsTest extends JSR166TestCase{
15 > public class ExecutorsTest extends JSR166TestCase {
16      public static void main(String[] args) {
17 <        junit.textui.TestRunner.run (suite());  
17 >        junit.textui.TestRunner.run(suite());
18      }
19      public static Test suite() {
20          return new TestSuite(ExecutorsTest.class);
21      }
22  
25    static class TimedCallable<T> implements Callable<T> {
26        private final ExecutorService exec;
27        private final Callable<T> func;
28        private final long msecs;
29        
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 = exec.submit(func);
38            try {
39                return ftask.get(msecs, TimeUnit.MILLISECONDS);
40            } finally {
41                ftask.cancel(true);
42            }
43        }
44    }
45
46
47    private static class Fib implements Callable<BigInteger> {
48        private final BigInteger n;
49        Fib(long n) {
50            if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
51            this.n = BigInteger.valueOf(n);
52        }
53        public BigInteger call() {
54            BigInteger f1 = BigInteger.ONE;
55            BigInteger f2 = f1;
56            for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
57                BigInteger t = f1.add(f2);
58                f1 = f2;
59                f2 = t;
60            }
61            return f1;
62        }
63    };
64
23      /**
24       * A newCachedThreadPool can execute runnables
25       */
# Line 91 | Line 49 | public class ExecutorsTest extends JSR16
49          try {
50              ExecutorService e = Executors.newCachedThreadPool(null);
51              shouldThrow();
52 <        }
95 <        catch(NullPointerException success) {
96 <        }
52 >        } catch (NullPointerException success) {}
53      }
54  
99
55      /**
56       * A new SingleThreadExecutor can execute runnables
57       */
# Line 126 | Line 81 | public class ExecutorsTest extends JSR16
81          try {
82              ExecutorService e = Executors.newSingleThreadExecutor(null);
83              shouldThrow();
84 <        }
130 <        catch(NullPointerException success) {
131 <        }
84 >        } catch (NullPointerException success) {}
85      }
86  
87      /**
# Line 138 | Line 91 | public class ExecutorsTest extends JSR16
91          ExecutorService e = Executors.newSingleThreadExecutor();
92          try {
93              ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
94 +            shouldThrow();
95          } catch (ClassCastException success) {
96          } finally {
97              joinPool(e);
98          }
99      }
100  
147
101      /**
102       * A new newFixedThreadPool can execute runnables
103       */
# Line 174 | Line 127 | public class ExecutorsTest extends JSR16
127          try {
128              ExecutorService e = Executors.newFixedThreadPool(2, null);
129              shouldThrow();
130 <        }
178 <        catch(NullPointerException success) {
179 <        }
130 >        } catch (NullPointerException success) {}
131      }
132  
133      /**
# Line 186 | Line 137 | public class ExecutorsTest extends JSR16
137          try {
138              ExecutorService e = Executors.newFixedThreadPool(0);
139              shouldThrow();
140 <        }
190 <        catch(IllegalArgumentException success) {
191 <        }
140 >        } catch (IllegalArgumentException success) {}
141      }
142  
194
143      /**
144       * An unconfigurable newFixedThreadPool can execute runnables
145       */
# Line 209 | Line 157 | public class ExecutorsTest extends JSR16
157      public void testunconfigurableExecutorServiceNPE() {
158          try {
159              ExecutorService e = Executors.unconfigurableExecutorService(null);
160 <        }
161 <        catch (NullPointerException success) {
214 <        }
160 >            shouldThrow();
161 >        } catch (NullPointerException success) {}
162      }
163  
164      /**
# Line 220 | Line 167 | public class ExecutorsTest extends JSR16
167      public void testunconfigurableScheduledExecutorServiceNPE() {
168          try {
169              ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
170 <        }
171 <        catch (NullPointerException success) {
225 <        }
170 >            shouldThrow();
171 >        } catch (NullPointerException success) {}
172      }
173  
228
174      /**
175       * a newSingleThreadScheduledExecutor successfully runs delayed task
176       */
177 <    public void testNewSingleThreadScheduledExecutor() {
178 <        try {
179 <            TrackedCallable callable = new TrackedCallable();
180 <            ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
181 <            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
182 <            assertFalse(callable.done);
183 <            Thread.sleep(MEDIUM_DELAY_MS);
184 <            assertTrue(callable.done);
185 <            assertEquals(Boolean.TRUE, f.get());
186 <            joinPool(p1);
187 <        } catch(RejectedExecutionException e){}
188 <        catch(Exception e){
189 <            e.printStackTrace();
190 <            unexpectedException();
177 >    public void testNewSingleThreadScheduledExecutor() throws Exception {
178 >        ScheduledExecutorService p = Executors.newSingleThreadScheduledExecutor();
179 >        try {
180 >            final CountDownLatch done = new CountDownLatch(1);
181 >            final Runnable task = new CheckedRunnable() {
182 >                public void realRun() {
183 >                    done.countDown();
184 >                }};
185 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
186 >                                  SHORT_DELAY_MS, MILLISECONDS);
187 >            assertFalse(f.isDone());
188 >            assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
189 >            assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
190 >            assertSame(Boolean.TRUE, f.get());
191 >            assertTrue(f.isDone());
192 >        } finally {
193 >            joinPool(p);
194          }
195      }
196  
197      /**
198       * a newScheduledThreadPool successfully runs delayed task
199       */
200 <    public void testnewScheduledThreadPool() {
201 <        try {
202 <            TrackedCallable callable = new TrackedCallable();
203 <            ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
204 <            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
205 <            assertFalse(callable.done);
206 <            Thread.sleep(MEDIUM_DELAY_MS);
207 <            assertTrue(callable.done);
208 <            assertEquals(Boolean.TRUE, f.get());
209 <            joinPool(p1);
210 <        } catch(RejectedExecutionException e){}
211 <        catch(Exception e){
212 <            e.printStackTrace();
213 <            unexpectedException();
200 >    public void testnewScheduledThreadPool() throws Exception {
201 >        ScheduledExecutorService p = Executors.newScheduledThreadPool(2);
202 >        try {
203 >            final CountDownLatch done = new CountDownLatch(1);
204 >            final Runnable task = new CheckedRunnable() {
205 >                public void realRun() {
206 >                    done.countDown();
207 >                }};
208 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
209 >                                  SHORT_DELAY_MS, MILLISECONDS);
210 >            assertFalse(f.isDone());
211 >            assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
212 >            assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
213 >            assertSame(Boolean.TRUE, f.get());
214 >            assertTrue(f.isDone());
215 >        } finally {
216 >            joinPool(p);
217          }
218      }
219  
220      /**
221 <     * an unconfigurable  newScheduledThreadPool successfully runs delayed task
221 >     * an unconfigurable newScheduledThreadPool successfully runs delayed task
222       */
223 <    public void testunconfigurableScheduledExecutorService() {
224 <        try {
225 <            TrackedCallable callable = new TrackedCallable();
226 <            ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
227 <            Future f = p1.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
228 <            assertFalse(callable.done);
229 <            Thread.sleep(MEDIUM_DELAY_MS);
230 <            assertTrue(callable.done);
231 <            assertEquals(Boolean.TRUE, f.get());
232 <            joinPool(p1);
233 <        } catch(RejectedExecutionException e){}
234 <        catch(Exception e){
235 <            e.printStackTrace();
236 <            unexpectedException();
223 >    public void testunconfigurableScheduledExecutorService() throws Exception {
224 >        ScheduledExecutorService p =
225 >            Executors.unconfigurableScheduledExecutorService
226 >            (Executors.newScheduledThreadPool(2));
227 >        try {
228 >            final CountDownLatch done = new CountDownLatch(1);
229 >            final Runnable task = new CheckedRunnable() {
230 >                public void realRun() {
231 >                    done.countDown();
232 >                }};
233 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
234 >                                  SHORT_DELAY_MS, MILLISECONDS);
235 >            assertFalse(f.isDone());
236 >            assertTrue(done.await(MEDIUM_DELAY_MS, MILLISECONDS));
237 >            assertSame(Boolean.TRUE, f.get(SMALL_DELAY_MS, MILLISECONDS));
238 >            assertSame(Boolean.TRUE, f.get());
239 >            assertTrue(f.isDone());
240 >        } finally {
241 >            joinPool(p);
242          }
243      }
244  
245      /**
246 <     *  timeouts from execute will time out if they compute too long.
246 >     * Future.get on submitted tasks will time out if they compute too long.
247       */
248 <    public void testTimedCallable() {
249 <        int N = 10000;
250 <        ExecutorService executor = Executors.newSingleThreadExecutor();
251 <        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
252 <        try {
253 <            long startTime = System.currentTimeMillis();
254 <            
255 <            long i = 0;
256 <            while (tasks.size() < N) {
257 <                tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
258 <                i += 10;
259 <            }
260 <            
261 <            int iters = 0;
262 <            BigInteger sum = BigInteger.ZERO;
263 <            for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
264 <                try {
265 <                    ++iters;
266 <                    sum = sum.add(it.next().call());
267 <                }
268 <                catch (TimeoutException success) {
269 <                    assertTrue(iters > 0);
270 <                    return;
271 <                }
272 <                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 <        finally {
248 >    public void testTimedCallable() throws Exception {
249 >        final ExecutorService[] executors = {
250 >            Executors.newSingleThreadExecutor(),
251 >            Executors.newCachedThreadPool(),
252 >            Executors.newFixedThreadPool(2),
253 >            Executors.newScheduledThreadPool(2),
254 >        };
255 >
256 >        final Runnable sleeper = new CheckedInterruptedRunnable() {
257 >            public void realRun() throws InterruptedException {
258 >                delay(LONG_DELAY_MS);
259 >            }};
260 >
261 >        List<Thread> threads = new ArrayList<Thread>();
262 >        for (final ExecutorService executor : executors) {
263 >            threads.add(newStartedThread(new CheckedRunnable() {
264 >                public void realRun() {
265 >                    long startTime = System.nanoTime();
266 >                    Future future = executor.submit(sleeper);
267 >                    assertFutureTimesOut(future);
268 >                }}));
269 >        }
270 >        for (Thread thread : threads)
271 >            awaitTermination(thread);
272 >        for (ExecutorService executor : executors)
273              joinPool(executor);
326        }
274      }
275  
329    
276      /**
277       * ThreadPoolExecutor using defaultThreadFactory has
278       * specified group, priority, daemon status, and name
279       */
280 <    public void testDefaultThreadFactory() {
280 >    public void testDefaultThreadFactory() throws Exception {
281          final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
282 <        Runnable r = new Runnable() {
283 <                public void run() {
284 <                    try {
285 <                        Thread current = Thread.currentThread();
286 <                        threadAssertTrue(!current.isDaemon());
287 <                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
288 <                        ThreadGroup g = current.getThreadGroup();
289 <                        SecurityManager s = System.getSecurityManager();
290 <                        if (s != null)
291 <                            threadAssertTrue(g == s.getThreadGroup());
292 <                        else
293 <                            threadAssertTrue(g == egroup);
294 <                        String name = current.getName();
295 <                        threadAssertTrue(name.endsWith("thread-1"));
296 <                    } catch (SecurityException ok) {
297 <                        // Also pass if not allowed to change setting
352 <                    }
282 >        Runnable r = new CheckedRunnable() {
283 >            public void realRun() {
284 >                try {
285 >                    Thread current = Thread.currentThread();
286 >                    assertTrue(!current.isDaemon());
287 >                    assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
288 >                    ThreadGroup g = current.getThreadGroup();
289 >                    SecurityManager s = System.getSecurityManager();
290 >                    if (s != null)
291 >                        assertTrue(g == s.getThreadGroup());
292 >                    else
293 >                        assertTrue(g == egroup);
294 >                    String name = current.getName();
295 >                    assertTrue(name.endsWith("thread-1"));
296 >                } catch (SecurityException ok) {
297 >                    // Also pass if not allowed to change setting
298                  }
299 <            };
299 >            }};
300          ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
301 <        
301 >
302          e.execute(r);
303          try {
304              e.shutdown();
305 <        } catch(SecurityException ok) {
305 >        } catch (SecurityException ok) {
306          }
307 <        
307 >
308          try {
309 <            Thread.sleep(SHORT_DELAY_MS);
365 <        } catch (Exception eX) {
366 <            unexpectedException();
309 >            delay(SHORT_DELAY_MS);
310          } finally {
311              joinPool(e);
312          }
# Line 374 | Line 317 | public class ExecutorsTest extends JSR16
317       * specified group, priority, daemon status, name,
318       * access control context and context class loader
319       */
320 <    public void testPrivilegedThreadFactory() {
321 <        Policy savedPolicy = null;
322 <        try {
323 <            savedPolicy = Policy.getPolicy();
324 <            AdjustablePolicy policy = new AdjustablePolicy();
325 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
326 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
327 <            Policy.setPolicy(policy);
328 <        } catch (AccessControlException ok) {
329 <            return;
330 <        }
331 <        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
332 <        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
333 <        final AccessControlContext thisacc = AccessController.getContext();
334 <        Runnable r = new Runnable() {
335 <                public void run() {
336 <                    try {
337 <                        Thread current = Thread.currentThread();
338 <                        threadAssertTrue(!current.isDaemon());
339 <                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
340 <                        ThreadGroup g = current.getThreadGroup();
341 <                        SecurityManager s = System.getSecurityManager();
342 <                        if (s != null)
343 <                            threadAssertTrue(g == s.getThreadGroup());
344 <                        else
345 <                            threadAssertTrue(g == egroup);
346 <                        String name = current.getName();
347 <                        threadAssertTrue(name.endsWith("thread-1"));
348 <                        threadAssertTrue(thisccl == current.getContextClassLoader());
349 <                        threadAssertTrue(thisacc.equals(AccessController.getContext()));
350 <                    } catch(SecurityException ok) {
351 <                        // Also pass if not allowed to change settings
352 <                    }
353 <                }
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 <        try {
421 <            Thread.sleep(SHORT_DELAY_MS);
422 <        } catch (Exception ex) {
423 <            unexpectedException();
424 <        } finally {
425 <            joinPool(e);
426 <        }
320 >    public void testPrivilegedThreadFactory() throws Exception {
321 >        Runnable r = new CheckedRunnable() {
322 >            public void realRun() throws Exception {
323 >                final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
324 >                final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
325 >                final AccessControlContext thisacc = AccessController.getContext();
326 >                Runnable r = new CheckedRunnable() {
327 >                    public void realRun() {
328 >                        Thread current = Thread.currentThread();
329 >                        assertTrue(!current.isDaemon());
330 >                        assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
331 >                        ThreadGroup g = current.getThreadGroup();
332 >                        SecurityManager s = System.getSecurityManager();
333 >                        if (s != null)
334 >                            assertTrue(g == s.getThreadGroup());
335 >                        else
336 >                            assertTrue(g == egroup);
337 >                        String name = current.getName();
338 >                        assertTrue(name.endsWith("thread-1"));
339 >                        assertSame(thisccl, current.getContextClassLoader());
340 >                        assertEquals(thisacc, AccessController.getContext());
341 >                    }};
342 >                ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
343 >                e.execute(r);
344 >                e.shutdown();
345 >                delay(SHORT_DELAY_MS);
346 >                joinPool(e);
347 >            }};
348 >
349 >        runWithPermissions(r,
350 >                           new RuntimePermission("getClassLoader"),
351 >                           new RuntimePermission("setContextClassLoader"),
352 >                           new RuntimePermission("modifyThread"));
353 >    }
354  
355 +    boolean haveCCLPermissions() {
356 +        SecurityManager sm = System.getSecurityManager();
357 +        if (sm != null) {
358 +            try {
359 +                sm.checkPermission(new RuntimePermission("setContextClassLoader"));
360 +                sm.checkPermission(new RuntimePermission("getClassLoader"));
361 +            } catch (AccessControlException e) {
362 +                return false;
363 +            }
364 +        }
365 +        return true;
366      }
367  
368      void checkCCL() {
369          SecurityManager sm = System.getSecurityManager();
370          if (sm != null) {
371              sm.checkPermission(new RuntimePermission("setContextClassLoader"));
372 <            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
372 >            sm.checkPermission(new RuntimePermission("getClassLoader"));
373          }
374      }
375  
# Line 442 | Line 380 | public class ExecutorsTest extends JSR16
380          }
381      }
382  
445
383      /**
384       * Without class loader permissions, creating
385       * privilegedCallableUsingCurrentClassLoader throws ACE
386       */
387      public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
388 <        Policy savedPolicy = null;
389 <        try {
390 <            savedPolicy = Policy.getPolicy();
391 <            AdjustablePolicy policy = new AdjustablePolicy();
392 <            Policy.setPolicy(policy);
393 <        } catch (AccessControlException ok) {
394 <            return;
395 <        }
396 <
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 <        }
388 >        Runnable r = new CheckedRunnable() {
389 >            public void realRun() throws Exception {
390 >                if (System.getSecurityManager() == null)
391 >                    return;
392 >                try {
393 >                    Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
394 >                    shouldThrow();
395 >                } catch (AccessControlException success) {}
396 >            }};
397  
398 <        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 <        }
398 >        runWithoutPermissions(r);
399      }
400  
401      /**
402       * With class loader permissions, calling
403       * privilegedCallableUsingCurrentClassLoader does not throw ACE
404       */
405 <    public void testprivilegedCallableUsingCCLWithPrivs() {
406 <        Policy savedPolicy = null;
407 <        try {
408 <            savedPolicy = Policy.getPolicy();
409 <            AdjustablePolicy policy = new AdjustablePolicy();
410 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
411 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
412 <            Policy.setPolicy(policy);
413 <        } catch (AccessControlException ok) {
414 <            return;
415 <        }
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 <        }
405 >    public void testprivilegedCallableUsingCCLWithPrivs() throws Exception {
406 >        Runnable r = new CheckedRunnable() {
407 >            public void realRun() throws Exception {
408 >                Executors.privilegedCallableUsingCurrentClassLoader
409 >                    (new NoOpCallable())
410 >                    .call();
411 >            }};
412 >
413 >        runWithPermissions(r,
414 >                           new RuntimePermission("getClassLoader"),
415 >                           new RuntimePermission("setContextClassLoader"));
416      }
417  
418      /**
419       * Without permissions, calling privilegedCallable throws ACE
420       */
421 <    public void testprivilegedCallableWithNoPrivs() {
422 <        Callable task;
423 <        Policy savedPolicy = null;
424 <        AdjustablePolicy policy = null;
425 <        AccessControlContext noprivAcc = null;
426 <        try {
427 <            savedPolicy = Policy.getPolicy();
428 <            policy = new AdjustablePolicy();
429 <            Policy.setPolicy(policy);
430 <            noprivAcc = AccessController.getContext();
431 <            task = Executors.privilegedCallable(new CheckCCL());
432 <            Policy.setPolicy(savedPolicy);
433 <        } catch (AccessControlException ok) {
434 <            return; // program has too few permissions to set up test
435 <        }
436 <
437 <        // Make sure that program doesn't have too many permissions
438 <        try {
439 <            AccessController.doPrivileged(new PrivilegedAction() {
440 <                    public Object run() {
441 <                        checkCCL();
442 <                        return null;
443 <                    }}, noprivAcc);
444 <            // too many permssions; skip test
445 <            return;
446 <        } catch(AccessControlException ok) {
447 <        }
448 <
449 <        try {
450 <            task.call();
451 <            shouldThrow();
452 <        } catch(AccessControlException success) {
453 <        } catch(Exception ex) {
454 <            unexpectedException();
455 <        }
421 >    public void testprivilegedCallableWithNoPrivs() throws Exception {
422 >        // Avoid classloader-related SecurityExceptions in swingui.TestRunner
423 >        Executors.privilegedCallable(new CheckCCL());
424 >
425 >        Runnable r = new CheckedRunnable() {
426 >            public void realRun() throws Exception {
427 >                if (System.getSecurityManager() == null)
428 >                    return;
429 >                Callable task = Executors.privilegedCallable(new CheckCCL());
430 >                try {
431 >                    task.call();
432 >                    shouldThrow();
433 >                } catch (AccessControlException success) {}
434 >            }};
435 >
436 >        runWithoutPermissions(r);
437 >
438 >        // It seems rather difficult to test that the
439 >        // AccessControlContext of the privilegedCallable is used
440 >        // instead of its caller.  Below is a failed attempt to do
441 >        // that, which does not work because the AccessController
442 >        // cannot capture the internal state of the current Policy.
443 >        // It would be much more work to differentiate based on,
444 >        // e.g. CodeSource.
445 >
446 > //         final AccessControlContext[] noprivAcc = new AccessControlContext[1];
447 > //         final Callable[] task = new Callable[1];
448 >
449 > //         runWithPermissions
450 > //             (new CheckedRunnable() {
451 > //                 public void realRun() {
452 > //                     if (System.getSecurityManager() == null)
453 > //                         return;
454 > //                     noprivAcc[0] = AccessController.getContext();
455 > //                     task[0] = Executors.privilegedCallable(new CheckCCL());
456 > //                     try {
457 > //                         AccessController.doPrivileged(new PrivilegedAction<Void>() {
458 > //                                                           public Void run() {
459 > //                                                               checkCCL();
460 > //                                                               return null;
461 > //                                                           }}, noprivAcc[0]);
462 > //                         shouldThrow();
463 > //                     } catch (AccessControlException success) {}
464 > //                 }});
465 >
466 > //         runWithPermissions
467 > //             (new CheckedRunnable() {
468 > //                 public void realRun() throws Exception {
469 > //                     if (System.getSecurityManager() == null)
470 > //                         return;
471 > //                     // Verify that we have an underprivileged ACC
472 > //                     try {
473 > //                         AccessController.doPrivileged(new PrivilegedAction<Void>() {
474 > //                                                           public Void run() {
475 > //                                                               checkCCL();
476 > //                                                               return null;
477 > //                                                           }}, noprivAcc[0]);
478 > //                         shouldThrow();
479 > //                     } catch (AccessControlException success) {}
480 >
481 > //                     try {
482 > //                         task[0].call();
483 > //                         shouldThrow();
484 > //                     } catch (AccessControlException success) {}
485 > //                 }},
486 > //              new RuntimePermission("getClassLoader"),
487 > //              new RuntimePermission("setContextClassLoader"));
488      }
489  
490      /**
491       * With permissions, calling privilegedCallable succeeds
492       */
493 <    public void testprivilegedCallableWithPrivs() {
494 <        Policy savedPolicy = null;
495 <        try {
496 <            savedPolicy = Policy.getPolicy();
497 <            AdjustablePolicy policy = new AdjustablePolicy();
498 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
499 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
500 <            Policy.setPolicy(policy);
501 <        } 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 <        }
493 >    public void testprivilegedCallableWithPrivs() throws Exception {
494 >        Runnable r = new CheckedRunnable() {
495 >            public void realRun() throws Exception {
496 >                Executors.privilegedCallable(new CheckCCL()).call();
497 >            }};
498 >
499 >        runWithPermissions(r,
500 >                           new RuntimePermission("getClassLoader"),
501 >                           new RuntimePermission("setContextClassLoader"));
502      }
503  
504      /**
505       * callable(Runnable) returns null when called
506 <     */
507 <    public void testCallable1() {
508 <        try {
509 <            Callable c = Executors.callable(new NoOpRunnable());
579 <            assertNull(c.call());
580 <        } catch(Exception ex) {
581 <            unexpectedException();
582 <        }
583 <        
506 >     */
507 >    public void testCallable1() throws Exception {
508 >        Callable c = Executors.callable(new NoOpRunnable());
509 >        assertNull(c.call());
510      }
511  
512      /**
513       * callable(Runnable, result) returns result when called
514 <     */
515 <    public void testCallable2() {
516 <        try {
517 <            Callable c = Executors.callable(new NoOpRunnable(), one);
592 <            assertEquals(one, c.call());
593 <        } catch(Exception ex) {
594 <            unexpectedException();
595 <        }
514 >     */
515 >    public void testCallable2() throws Exception {
516 >        Callable c = Executors.callable(new NoOpRunnable(), one);
517 >        assertSame(one, c.call());
518      }
519  
520      /**
521       * callable(PrivilegedAction) returns its result when called
522 <     */
523 <    public void testCallable3() {
524 <        try {
525 <            Callable c = Executors.callable(new PrivilegedAction() {
526 <                    public Object run() { return one; }});
605 <        assertEquals(one, c.call());
606 <        } catch(Exception ex) {
607 <            unexpectedException();
608 <        }
522 >     */
523 >    public void testCallable3() throws Exception {
524 >        Callable c = Executors.callable(new PrivilegedAction() {
525 >                public Object run() { return one; }});
526 >        assertSame(one, c.call());
527      }
528  
529      /**
530       * callable(PrivilegedExceptionAction) returns its result when called
531 <     */
532 <    public void testCallable4() {
533 <        try {
534 <            Callable c = Executors.callable(new PrivilegedExceptionAction() {
535 <                    public Object run() { return one; }});
618 <            assertEquals(one, c.call());
619 <        } catch(Exception ex) {
620 <            unexpectedException();
621 <        }
531 >     */
532 >    public void testCallable4() throws Exception {
533 >        Callable c = Executors.callable(new PrivilegedExceptionAction() {
534 >                public Object run() { return one; }});
535 >        assertSame(one, c.call());
536      }
537  
624
538      /**
539       * callable(null Runnable) throws NPE
540 <     */
540 >     */
541      public void testCallableNPE1() {
542          try {
543 <            Runnable r = null;
544 <            Callable c = Executors.callable(r);
545 <        } catch (NullPointerException success) {
633 <        }
543 >            Callable c = Executors.callable((Runnable) null);
544 >            shouldThrow();
545 >        } catch (NullPointerException success) {}
546      }
547  
548      /**
549       * callable(null, result) throws NPE
550 <     */
550 >     */
551      public void testCallableNPE2() {
552          try {
553 <            Runnable r = null;
554 <            Callable c = Executors.callable(r, one);
555 <        } catch (NullPointerException success) {
644 <        }
553 >            Callable c = Executors.callable((Runnable) null, one);
554 >            shouldThrow();
555 >        } catch (NullPointerException success) {}
556      }
557  
558      /**
559       * callable(null PrivilegedAction) throws NPE
560 <     */
560 >     */
561      public void testCallableNPE3() {
562          try {
563 <            PrivilegedAction r = null;
564 <            Callable c = Executors.callable(r);
565 <        } catch (NullPointerException success) {
655 <        }
563 >            Callable c = Executors.callable((PrivilegedAction) null);
564 >            shouldThrow();
565 >        } catch (NullPointerException success) {}
566      }
567  
568      /**
569       * callable(null PrivilegedExceptionAction) throws NPE
570 <     */
570 >     */
571      public void testCallableNPE4() {
572          try {
573 <            PrivilegedExceptionAction r = null;
574 <            Callable c = Executors.callable(r);
575 <        } catch (NullPointerException success) {
666 <        }
573 >            Callable c = Executors.callable((PrivilegedExceptionAction) null);
574 >            shouldThrow();
575 >        } catch (NullPointerException success) {}
576      }
577  
669
578   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines