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.26 by jsr166, Sat Nov 21 02:33:20 2009 UTC vs.
Revision 1.35 by jsr166, Mon Oct 11 08:47:04 2010 UTC

# Line 16 | Line 16 | import java.security.*;
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);
23      }
24  
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, 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
25      /**
26       * A newCachedThreadPool can execute runnables
27       */
# Line 221 | Line 181 | public class ExecutorsTest extends JSR16
181       * a newSingleThreadScheduledExecutor successfully runs delayed task
182       */
183      public void testNewSingleThreadScheduledExecutor() throws Exception {
184 <        TrackedCallable callable = new TrackedCallable();
185 <        ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
186 <        Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
187 <        assertFalse(callable.done);
188 <        Thread.sleep(MEDIUM_DELAY_MS);
189 <        assertTrue(callable.done);
190 <        assertEquals(Boolean.TRUE, f.get());
191 <        joinPool(p1);
184 >        ScheduledExecutorService p = Executors.newSingleThreadScheduledExecutor();
185 >        try {
186 >            final CountDownLatch done = new CountDownLatch(1);
187 >            final Runnable task = new CheckedRunnable() {
188 >                public void realRun() {
189 >                    done.countDown();
190 >                }};
191 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
192 >                                  SHORT_DELAY_MS, MILLISECONDS);
193 >            assertFalse(f.isDone());
194 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
195 >            assertTrue(f.isDone());
196 >            assertEquals(Boolean.TRUE, f.get());
197 >        } finally {
198 >            joinPool(p);
199 >        }
200      }
201  
202      /**
203       * a newScheduledThreadPool successfully runs delayed task
204       */
205      public void testnewScheduledThreadPool() throws Exception {
206 <        TrackedCallable callable = new TrackedCallable();
207 <        ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
208 <        Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
209 <        assertFalse(callable.done);
210 <        Thread.sleep(MEDIUM_DELAY_MS);
211 <        assertTrue(callable.done);
212 <        assertEquals(Boolean.TRUE, f.get());
213 <        joinPool(p1);
206 >        ScheduledExecutorService p = Executors.newScheduledThreadPool(2);
207 >        try {
208 >            final CountDownLatch done = new CountDownLatch(1);
209 >            final Runnable task = new CheckedRunnable() {
210 >                public void realRun() {
211 >                    done.countDown();
212 >                }};
213 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
214 >                                  SHORT_DELAY_MS, MILLISECONDS);
215 >            assertFalse(f.isDone());
216 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
217 >            assertTrue(f.isDone());
218 >            assertEquals(Boolean.TRUE, f.get());
219 >        } finally {
220 >            joinPool(p);
221 >        }
222      }
223  
224      /**
225       * an unconfigurable newScheduledThreadPool successfully runs delayed task
226       */
227      public void testunconfigurableScheduledExecutorService() throws Exception {
228 <        TrackedCallable callable = new TrackedCallable();
229 <        ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
230 <        Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
231 <        assertFalse(callable.done);
232 <        Thread.sleep(MEDIUM_DELAY_MS);
233 <        assertTrue(callable.done);
234 <        assertEquals(Boolean.TRUE, f.get());
235 <        joinPool(p1);
228 >        ScheduledExecutorService p =
229 >            Executors.unconfigurableScheduledExecutorService
230 >            (Executors.newScheduledThreadPool(2));
231 >        try {
232 >            final CountDownLatch done = new CountDownLatch(1);
233 >            final Runnable task = new CheckedRunnable() {
234 >                public void realRun() {
235 >                    done.countDown();
236 >                }};
237 >            Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
238 >                                  SHORT_DELAY_MS, MILLISECONDS);
239 >            assertFalse(f.isDone());
240 >            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
241 >            assertTrue(f.isDone());
242 >            assertEquals(Boolean.TRUE, f.get());
243 >        } finally {
244 >            joinPool(p);
245 >        }
246      }
247  
248      /**
249 <     *  timeouts from execute will time out if they compute too long.
249 >     * Future.get on submitted tasks will time out if they compute too long.
250       */
251      public void testTimedCallable() throws Exception {
252 <        int N = 10000;
253 <        ExecutorService executor = Executors.newSingleThreadExecutor();
254 <        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
255 <        try {
256 <            long startTime = System.currentTimeMillis();
257 <
258 <            long i = 0;
259 <            while (tasks.size() < N) {
260 <                tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
261 <                i += 10;
262 <            }
263 <
264 <            int iters = 0;
279 <            BigInteger sum = BigInteger.ZERO;
280 <            for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
252 >        final Runnable sleeper = new CheckedInterruptedRunnable() {
253 >            public void realRun() throws InterruptedException {
254 >                Thread.sleep(LONG_DELAY_MS);
255 >            }};
256 >        for (ExecutorService executor :
257 >                 new ExecutorService[] {
258 >                     Executors.newSingleThreadExecutor(),
259 >                     Executors.newCachedThreadPool(),
260 >                     Executors.newFixedThreadPool(2),
261 >                     Executors.newScheduledThreadPool(2),
262 >                 }) {
263 >            try {
264 >                Future future = executor.submit(sleeper);
265                  try {
266 <                    ++iters;
267 <                    sum = sum.add(it.next().call());
268 <                }
269 <                catch (TimeoutException success) {
270 <                    assertTrue(iters > 0);
287 <                    return;
266 >                    future.get(SHORT_DELAY_MS, MILLISECONDS);
267 >                    shouldThrow();
268 >                } catch (TimeoutException success) {
269 >                } finally {
270 >                    future.cancel(true);
271                  }
272              }
273 <            // if by chance we didn't ever time out, total time must be small
274 <            long elapsed = System.currentTimeMillis() - startTime;
275 <            assertTrue(elapsed < N);
293 <        }
294 <        finally {
295 <            joinPool(executor);
273 >            finally {
274 >                joinPool(executor);
275 >            }
276          }
277      }
278  
# Line 303 | Line 283 | public class ExecutorsTest extends JSR16
283       */
284      public void testDefaultThreadFactory() throws Exception {
285          final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
286 <        Runnable r = new Runnable() {
287 <                public void run() {
288 <                    try {
289 <                        Thread current = Thread.currentThread();
290 <                        threadAssertTrue(!current.isDaemon());
291 <                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
292 <                        ThreadGroup g = current.getThreadGroup();
293 <                        SecurityManager s = System.getSecurityManager();
294 <                        if (s != null)
295 <                            threadAssertTrue(g == s.getThreadGroup());
296 <                        else
297 <                            threadAssertTrue(g == egroup);
298 <                        String name = current.getName();
299 <                        threadAssertTrue(name.endsWith("thread-1"));
300 <                    } catch (SecurityException ok) {
301 <                        // Also pass if not allowed to change setting
322 <                    }
286 >        Runnable r = new CheckedRunnable() {
287 >            public void realRun() {
288 >                try {
289 >                    Thread current = Thread.currentThread();
290 >                    assertTrue(!current.isDaemon());
291 >                    assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
292 >                    ThreadGroup g = current.getThreadGroup();
293 >                    SecurityManager s = System.getSecurityManager();
294 >                    if (s != null)
295 >                        assertTrue(g == s.getThreadGroup());
296 >                    else
297 >                        assertTrue(g == egroup);
298 >                    String name = current.getName();
299 >                    assertTrue(name.endsWith("thread-1"));
300 >                } catch (SecurityException ok) {
301 >                    // Also pass if not allowed to change setting
302                  }
303 <            };
303 >            }};
304          ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
305  
306          e.execute(r);
# Line 343 | Line 322 | public class ExecutorsTest extends JSR16
322       * access control context and context class loader
323       */
324      public void testPrivilegedThreadFactory() throws Exception {
325 <        Policy savedPolicy = null;
326 <        try {
327 <            savedPolicy = Policy.getPolicy();
328 <            AdjustablePolicy policy = new AdjustablePolicy();
329 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
330 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
331 <            Policy.setPolicy(policy);
353 <        } catch (AccessControlException ok) {
354 <            return;
355 <        }
356 <        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
357 <        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
358 <        final AccessControlContext thisacc = AccessController.getContext();
359 <        Runnable r = new Runnable() {
360 <                public void run() {
361 <                    try {
325 >        Runnable r = new CheckedRunnable() {
326 >            public void realRun() throws Exception {
327 >                final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
328 >                final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
329 >                final AccessControlContext thisacc = AccessController.getContext();
330 >                Runnable r = new CheckedRunnable() {
331 >                    public void realRun() {
332                          Thread current = Thread.currentThread();
333 <                        threadAssertTrue(!current.isDaemon());
334 <                        threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
333 >                        assertTrue(!current.isDaemon());
334 >                        assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
335                          ThreadGroup g = current.getThreadGroup();
336                          SecurityManager s = System.getSecurityManager();
337                          if (s != null)
338 <                            threadAssertTrue(g == s.getThreadGroup());
338 >                            assertTrue(g == s.getThreadGroup());
339                          else
340 <                            threadAssertTrue(g == egroup);
340 >                            assertTrue(g == egroup);
341                          String name = current.getName();
342 <                        threadAssertTrue(name.endsWith("thread-1"));
343 <                        threadAssertTrue(thisccl == current.getContextClassLoader());
344 <                        threadAssertTrue(thisacc.equals(AccessController.getContext()));
345 <                    } catch (SecurityException ok) {
346 <                        // Also pass if not allowed to change settings
347 <                    }
348 <                }
349 <            };
350 <        ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
342 >                        assertTrue(name.endsWith("thread-1"));
343 >                        assertSame(thisccl, current.getContextClassLoader());
344 >                        assertEquals(thisacc, AccessController.getContext());
345 >                    }};
346 >                ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
347 >                e.execute(r);
348 >                e.shutdown();
349 >                Thread.sleep(SHORT_DELAY_MS);
350 >                joinPool(e);
351 >            }};
352 >
353 >        runWithPermissions(r,
354 >                           new RuntimePermission("getClassLoader"),
355 >                           new RuntimePermission("setContextClassLoader"),
356 >                           new RuntimePermission("modifyThread"));
357 >    }
358  
359 <        Policy.setPolicy(savedPolicy);
360 <        e.execute(r);
361 <        try {
362 <            e.shutdown();
363 <        } catch (SecurityException ok) {
364 <        }
365 <        try {
366 <            Thread.sleep(SHORT_DELAY_MS);
367 <        } finally {
391 <            joinPool(e);
359 >    boolean haveCCLPermissions() {
360 >        SecurityManager sm = System.getSecurityManager();
361 >        if (sm != null) {
362 >            try {
363 >                sm.checkPermission(new RuntimePermission("setContextClassLoader"));
364 >                sm.checkPermission(new RuntimePermission("getClassLoader"));
365 >            } catch (AccessControlException e) {
366 >                return false;
367 >            }
368          }
369 <
369 >        return true;
370      }
371  
372      void checkCCL() {
# Line 414 | Line 390 | public class ExecutorsTest extends JSR16
390       * privilegedCallableUsingCurrentClassLoader throws ACE
391       */
392      public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
393 <        Policy savedPolicy = null;
394 <        try {
395 <            savedPolicy = Policy.getPolicy();
396 <            AdjustablePolicy policy = new AdjustablePolicy();
397 <            Policy.setPolicy(policy);
398 <        } catch (AccessControlException ok) {
399 <            return;
400 <        }
401 <
426 <        // Check if program still has too many permissions to run test
427 <        try {
428 <            checkCCL();
429 <            // too many privileges to test; so return
430 <            Policy.setPolicy(savedPolicy);
431 <            return;
432 <        } catch (AccessControlException ok) {
433 <        }
393 >        Runnable r = new CheckedRunnable() {
394 >            public void realRun() throws Exception {
395 >                if (System.getSecurityManager() == null)
396 >                    return;
397 >                try {
398 >                    Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
399 >                    shouldThrow();
400 >                } catch (AccessControlException success) {}
401 >            }};
402  
403 <        try {
436 <            Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
437 <            shouldThrow();
438 <        } catch (AccessControlException success) {
439 <        } finally {
440 <            Policy.setPolicy(savedPolicy);
441 <        }
403 >        runWithoutPermissions(r);
404      }
405  
406      /**
# Line 446 | Line 408 | public class ExecutorsTest extends JSR16
408       * privilegedCallableUsingCurrentClassLoader does not throw ACE
409       */
410      public void testprivilegedCallableUsingCCLWithPrivs() throws Exception {
411 <        Policy savedPolicy = null;
412 <        try {
413 <            savedPolicy = Policy.getPolicy();
414 <            AdjustablePolicy policy = new AdjustablePolicy();
415 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
416 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
417 <            Policy.setPolicy(policy);
418 <        } catch (AccessControlException ok) {
419 <            return;
420 <        }
459 <
460 <        try {
461 <            Callable task = Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
462 <            task.call();
463 <        }
464 <        finally {
465 <            Policy.setPolicy(savedPolicy);
466 <        }
411 >        Runnable r = new CheckedRunnable() {
412 >            public void realRun() throws Exception {
413 >                Executors.privilegedCallableUsingCurrentClassLoader
414 >                    (new NoOpCallable())
415 >                    .call();
416 >            }};
417 >
418 >        runWithPermissions(r,
419 >                           new RuntimePermission("getClassLoader"),
420 >                           new RuntimePermission("setContextClassLoader"));
421      }
422  
423      /**
424       * Without permissions, calling privilegedCallable throws ACE
425       */
426      public void testprivilegedCallableWithNoPrivs() throws Exception {
427 <        Callable task;
428 <        Policy savedPolicy = null;
475 <        AdjustablePolicy policy = null;
476 <        AccessControlContext noprivAcc = null;
477 <        try {
478 <            savedPolicy = Policy.getPolicy();
479 <            policy = new AdjustablePolicy();
480 <            Policy.setPolicy(policy);
481 <            noprivAcc = AccessController.getContext();
482 <            task = Executors.privilegedCallable(new CheckCCL());
483 <            Policy.setPolicy(savedPolicy);
484 <        } catch (AccessControlException ok) {
485 <            return; // program has too few permissions to set up test
486 <        }
487 <
488 <        // Make sure that program doesn't have too many permissions
489 <        try {
490 <            AccessController.doPrivileged(new PrivilegedAction() {
491 <                    public Object run() {
492 <                        checkCCL();
493 <                        return null;
494 <                    }}, noprivAcc);
495 <            // too many permssions; skip test
496 <            return;
497 <        } catch (AccessControlException ok) {
498 <        }
427 >        // Avoid classloader-related SecurityExceptions in swingui.TestRunner
428 >        Executors.privilegedCallable(new CheckCCL());
429  
430 <        try {
431 <            task.call();
432 <            shouldThrow();
433 <        } catch (AccessControlException success) {}
430 >        Runnable r = new CheckedRunnable() {
431 >            public void realRun() throws Exception {
432 >                if (System.getSecurityManager() == null)
433 >                    return;
434 >                Callable task = Executors.privilegedCallable(new CheckCCL());
435 >                try {
436 >                    task.call();
437 >                    shouldThrow();
438 >                } catch (AccessControlException success) {}
439 >            }};
440 >
441 >        runWithoutPermissions(r);
442 >
443 >        // It seems rather difficult to test that the
444 >        // AccessControlContext of the privilegedCallable is used
445 >        // instead of its caller.  Below is a failed attempt to do
446 >        // that, which does not work because the AccessController
447 >        // cannot capture the internal state of the current Policy.
448 >        // It would be much more work to differentiate based on,
449 >        // e.g. CodeSource.
450 >
451 > //         final AccessControlContext[] noprivAcc = new AccessControlContext[1];
452 > //         final Callable[] task = new Callable[1];
453 >
454 > //         runWithPermissions
455 > //             (new CheckedRunnable() {
456 > //                 public void realRun() {
457 > //                     if (System.getSecurityManager() == null)
458 > //                         return;
459 > //                     noprivAcc[0] = AccessController.getContext();
460 > //                     task[0] = Executors.privilegedCallable(new CheckCCL());
461 > //                     try {
462 > //                         AccessController.doPrivileged(new PrivilegedAction<Void>() {
463 > //                                                           public Void run() {
464 > //                                                               checkCCL();
465 > //                                                               return null;
466 > //                                                           }}, noprivAcc[0]);
467 > //                         shouldThrow();
468 > //                     } catch (AccessControlException success) {}
469 > //                 }});
470 >
471 > //         runWithPermissions
472 > //             (new CheckedRunnable() {
473 > //                 public void realRun() throws Exception {
474 > //                     if (System.getSecurityManager() == null)
475 > //                         return;
476 > //                     // Verify that we have an underprivileged ACC
477 > //                     try {
478 > //                         AccessController.doPrivileged(new PrivilegedAction<Void>() {
479 > //                                                           public Void run() {
480 > //                                                               checkCCL();
481 > //                                                               return null;
482 > //                                                           }}, noprivAcc[0]);
483 > //                         shouldThrow();
484 > //                     } catch (AccessControlException success) {}
485 >
486 > //                     try {
487 > //                         task[0].call();
488 > //                         shouldThrow();
489 > //                     } catch (AccessControlException success) {}
490 > //                 }},
491 > //              new RuntimePermission("getClassLoader"),
492 > //              new RuntimePermission("setContextClassLoader"));
493      }
494  
495      /**
496       * With permissions, calling privilegedCallable succeeds
497       */
498      public void testprivilegedCallableWithPrivs() throws Exception {
499 <        Policy savedPolicy = null;
500 <        try {
501 <            savedPolicy = Policy.getPolicy();
502 <            AdjustablePolicy policy = new AdjustablePolicy();
503 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
504 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
505 <            Policy.setPolicy(policy);
506 <        } catch (AccessControlException ok) {
518 <            return;
519 <        }
520 <
521 <        Callable task = Executors.privilegedCallable(new CheckCCL());
522 <        try {
523 <            task.call();
524 <        } finally {
525 <            Policy.setPolicy(savedPolicy);
526 <        }
499 >        Runnable r = new CheckedRunnable() {
500 >            public void realRun() throws Exception {
501 >                Executors.privilegedCallable(new CheckCCL()).call();
502 >            }};
503 >
504 >         runWithPermissions(r,
505 >                           new RuntimePermission("getClassLoader"),
506 >                           new RuntimePermission("setContextClassLoader"));
507      }
508  
509      /**
# Line 539 | Line 519 | public class ExecutorsTest extends JSR16
519       */
520      public void testCallable2() throws Exception {
521          Callable c = Executors.callable(new NoOpRunnable(), one);
522 <        assertEquals(one, c.call());
522 >        assertSame(one, c.call());
523      }
524  
525      /**
# Line 548 | Line 528 | public class ExecutorsTest extends JSR16
528      public void testCallable3() throws Exception {
529          Callable c = Executors.callable(new PrivilegedAction() {
530                  public Object run() { return one; }});
531 <        assertEquals(one, c.call());
531 >        assertSame(one, c.call());
532      }
533  
534      /**
# Line 557 | Line 537 | public class ExecutorsTest extends JSR16
537      public void testCallable4() throws Exception {
538          Callable c = Executors.callable(new PrivilegedExceptionAction() {
539                  public Object run() { return one; }});
540 <        assertEquals(one, c.call());
540 >        assertSame(one, c.call());
541      }
542  
543  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines