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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines