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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines