ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/AbstractExecutorServiceTest.java
(Generate patch)

Comparing jsr166/src/test/tck/AbstractExecutorServiceTest.java (file contents):
Revision 1.22 by jsr166, Tue Dec 1 22:51:44 2009 UTC vs.
Revision 1.37 by jsr166, Sat Apr 25 04:55:30 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9
10 import junit.framework.*;
11 import java.util.*;
12 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.math.BigInteger;
11 < import java.security.*;
10 >
11 > import java.security.PrivilegedAction;
12 > import java.security.PrivilegedExceptionAction;
13 > import java.util.ArrayList;
14 > import java.util.Collections;
15 > import java.util.List;
16 > import java.util.concurrent.AbstractExecutorService;
17 > import java.util.concurrent.ArrayBlockingQueue;
18 > import java.util.concurrent.Callable;
19 > import java.util.concurrent.CountDownLatch;
20 > import java.util.concurrent.ExecutionException;
21 > import java.util.concurrent.Executors;
22 > import java.util.concurrent.ExecutorService;
23 > import java.util.concurrent.Future;
24 > import java.util.concurrent.ThreadPoolExecutor;
25 > import java.util.concurrent.TimeUnit;
26 > import java.util.concurrent.atomic.AtomicBoolean;
27 >
28 > import junit.framework.Test;
29 > import junit.framework.TestSuite;
30  
31   public class AbstractExecutorServiceTest extends JSR166TestCase {
32      public static void main(String[] args) {
33 <        junit.textui.TestRunner.run (suite());
33 >        main(suite(), args);
34      }
35      public static Test suite() {
36          return new TestSuite(AbstractExecutorServiceTest.class);
# Line 29 | Line 43 | public class AbstractExecutorServiceTest
43      static class DirectExecutorService extends AbstractExecutorService {
44          public void execute(Runnable r) { r.run(); }
45          public void shutdown() { shutdown = true; }
46 <        public List<Runnable> shutdownNow() { shutdown = true; return Collections.EMPTY_LIST; }
46 >        public List<Runnable> shutdownNow() {
47 >            shutdown = true;
48 >            return Collections.EMPTY_LIST;
49 >        }
50          public boolean isShutdown() { return shutdown; }
51          public boolean isTerminated() { return isShutdown(); }
52 <        public boolean awaitTermination(long timeout, TimeUnit unit) { return isShutdown(); }
52 >        public boolean awaitTermination(long timeout, TimeUnit unit) {
53 >            return isShutdown();
54 >        }
55          private volatile boolean shutdown = false;
56      }
57  
# Line 41 | Line 60 | public class AbstractExecutorServiceTest
60       */
61      public void testExecuteRunnable() throws Exception {
62          ExecutorService e = new DirectExecutorService();
63 <        TrackedShortRunnable task = new TrackedShortRunnable();
64 <        assertFalse(task.done);
65 <        Future<?> future = e.submit(task);
66 <        future.get();
67 <        assertTrue(task.done);
63 >        final AtomicBoolean done = new AtomicBoolean(false);
64 >        Future<?> future = e.submit(new CheckedRunnable() {
65 >            public void realRun() {
66 >                done.set(true);
67 >            }});
68 >        assertNull(future.get());
69 >        assertNull(future.get(0, MILLISECONDS));
70 >        assertTrue(done.get());
71 >        assertTrue(future.isDone());
72 >        assertFalse(future.isCancelled());
73      }
74  
51
75      /**
76       * Completed submit(callable) returns result
77       */
# Line 79 | Line 102 | public class AbstractExecutorServiceTest
102          assertSame(TEST_STRING, result);
103      }
104  
82
105      /**
106 <     * A submitted privileged action to completion
106 >     * A submitted privileged action runs to completion
107       */
108      public void testSubmitPrivilegedAction() throws Exception {
109 <        Policy savedPolicy = null;
110 <        try {
111 <            savedPolicy = Policy.getPolicy();
112 <            AdjustablePolicy policy = new AdjustablePolicy();
91 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
92 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
93 <            Policy.setPolicy(policy);
94 <        } catch (AccessControlException ok) {
95 <            return;
96 <        }
97 <        try {
98 <            ExecutorService e = new DirectExecutorService();
99 <            Future future = e.submit(Executors.callable(new PrivilegedAction() {
109 >        Runnable r = new CheckedRunnable() {
110 >            public void realRun() throws Exception {
111 >                ExecutorService e = new DirectExecutorService();
112 >                Future future = e.submit(Executors.callable(new PrivilegedAction() {
113                      public Object run() {
114                          return TEST_STRING;
115                      }}));
116  
117 <            Object result = future.get();
118 <            assertSame(TEST_STRING, result);
119 <        }
120 <        finally {
121 <            try {
122 <                Policy.setPolicy(savedPolicy);
123 <            } catch (AccessControlException ok) {
111 <                return;
112 <            }
113 <        }
117 >                assertSame(TEST_STRING, future.get());
118 >            }};
119 >
120 >        runWithPermissions(r,
121 >                           new RuntimePermission("getClassLoader"),
122 >                           new RuntimePermission("setContextClassLoader"),
123 >                           new RuntimePermission("modifyThread"));
124      }
125  
126      /**
127 <     * A submitted a privileged exception action runs to completion
127 >     * A submitted privileged exception action runs to completion
128       */
129      public void testSubmitPrivilegedExceptionAction() throws Exception {
130 <        Policy savedPolicy = null;
131 <        try {
132 <            savedPolicy = Policy.getPolicy();
133 <            AdjustablePolicy policy = new AdjustablePolicy();
124 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
125 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
126 <            Policy.setPolicy(policy);
127 <        } catch (AccessControlException ok) {
128 <            return;
129 <        }
130 <
131 <        try {
132 <            ExecutorService e = new DirectExecutorService();
133 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
130 >        Runnable r = new CheckedRunnable() {
131 >            public void realRun() throws Exception {
132 >                ExecutorService e = new DirectExecutorService();
133 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
134                      public Object run() {
135                          return TEST_STRING;
136                      }}));
137  
138 <            Object result = future.get();
139 <            assertSame(TEST_STRING, result);
140 <        }
141 <        finally {
142 <            Policy.setPolicy(savedPolicy);
143 <        }
138 >                assertSame(TEST_STRING, future.get());
139 >            }};
140 >
141 >        runWithPermissions(r);
142      }
143  
144      /**
145       * A submitted failed privileged exception action reports exception
146       */
147      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
148 <        Policy savedPolicy = null;
149 <        try {
150 <            savedPolicy = Policy.getPolicy();
151 <            AdjustablePolicy policy = new AdjustablePolicy();
154 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
155 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
156 <            Policy.setPolicy(policy);
157 <        } catch (AccessControlException ok) {
158 <            return;
159 <        }
160 <
161 <        try {
162 <            ExecutorService e = new DirectExecutorService();
163 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
148 >        Runnable r = new CheckedRunnable() {
149 >            public void realRun() throws Exception {
150 >                ExecutorService e = new DirectExecutorService();
151 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
152                      public Object run() throws Exception {
153                          throw new IndexOutOfBoundsException();
154                      }}));
155  
156 <            future.get();
157 <            shouldThrow();
158 <        } catch (ExecutionException success) {
159 <            assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
160 <        }
161 <        finally {
162 <            Policy.setPolicy(savedPolicy);
163 <        }
156 >                try {
157 >                    future.get();
158 >                    shouldThrow();
159 >                } catch (ExecutionException success) {
160 >                    assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
161 >                }}};
162 >
163 >        runWithPermissions(r);
164      }
165  
166      /**
167       * execute(null runnable) throws NPE
168       */
169      public void testExecuteNullRunnable() {
170 +        ExecutorService e = new DirectExecutorService();
171          try {
183            ExecutorService e = new DirectExecutorService();
172              e.submit((Runnable) null);
173              shouldThrow();
174          } catch (NullPointerException success) {}
175      }
176  
189
177      /**
178       * submit(null callable) throws NPE
179       */
180      public void testSubmitNullCallable() {
181 +        ExecutorService e = new DirectExecutorService();
182          try {
195            ExecutorService e = new DirectExecutorService();
183              e.submit((Callable) null);
184              shouldThrow();
185          } catch (NullPointerException success) {}
186      }
187  
188      /**
189 <     * submit(runnable) throws RejectedExecutionException if
203 <     * executor is saturated.
189 >     * submit(callable).get() throws InterruptedException if interrupted
190       */
191 <    public void testExecute1() {
192 <        ThreadPoolExecutor p =
193 <            new ThreadPoolExecutor(1, 1,
194 <                                   60, TimeUnit.SECONDS,
195 <                                   new ArrayBlockingQueue<Runnable>(1));
196 <        try {
197 <            for (int i = 0; i < 2; ++i)
198 <                p.submit(new MediumRunnable());
199 <            for (int i = 0; i < 2; ++i) {
200 <                try {
201 <                    p.submit(new MediumRunnable());
202 <                    shouldThrow();
203 <                } catch (RejectedExecutionException success) {}
204 <            }
205 <        } finally {
206 <            joinPool(p);
207 <        }
208 <    }
209 <
210 <    /**
211 <     * submit(callable) throws RejectedExecutionException
212 <     * if executor is saturated.
227 <     */
228 <    public void testExecute2() {
229 <        ThreadPoolExecutor p =
230 <            new ThreadPoolExecutor(1, 1,
231 <                                   60, TimeUnit.SECONDS,
232 <                                   new ArrayBlockingQueue<Runnable>(1));
233 <        try {
234 <            for (int i = 0; i < 2; ++i)
235 <                p.submit(new MediumRunnable());
236 <            for (int i = 0; i < 2; ++i) {
237 <                try {
238 <                    p.submit(new SmallCallable());
239 <                    shouldThrow();
240 <                } catch (RejectedExecutionException success) {}
241 <            }
191 >    public void testInterruptedSubmit() throws InterruptedException {
192 >        final CountDownLatch submitted    = new CountDownLatch(1);
193 >        final CountDownLatch quittingTime = new CountDownLatch(1);
194 >        final ExecutorService p
195 >            = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
196 >                                     new ArrayBlockingQueue<Runnable>(10));
197 >        final Callable<Void> awaiter = new CheckedCallable<Void>() {
198 >            public Void realCall() throws InterruptedException {
199 >                quittingTime.await();
200 >                return null;
201 >            }};
202 >        try {
203 >            Thread t = new Thread(new CheckedInterruptedRunnable() {
204 >                public void realRun() throws Exception {
205 >                    Future<Void> future = p.submit(awaiter);
206 >                    submitted.countDown();
207 >                    future.get();
208 >                }});
209 >            t.start();
210 >            submitted.await();
211 >            t.interrupt();
212 >            t.join();
213          } finally {
214 +            quittingTime.countDown();
215              joinPool(p);
216          }
217      }
218  
247
219      /**
220 <     *  Blocking on submit(callable) throws InterruptedException if
221 <     *  caller interrupted.
251 <     */
252 <    public void testInterruptedSubmit() throws InterruptedException {
253 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
254 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
255 <            public void realRun() throws Exception {
256 <                p.submit(new CheckedCallable<Object>() {
257 <                             public Object realCall()
258 <                                 throws InterruptedException {
259 <                                 Thread.sleep(SMALL_DELAY_MS);
260 <                                 return null;
261 <                             }}).get();
262 <            }});
263 <
264 <        t.start();
265 <        Thread.sleep(SHORT_DELAY_MS);
266 <        t.interrupt();
267 <        joinPool(p);
268 <    }
269 <
270 <    /**
271 <     *  get of submitted callable throws InterruptedException if callable
272 <     *  interrupted
273 <     */
274 <    public void testSubmitIE() throws InterruptedException {
275 <        final ThreadPoolExecutor p =
276 <            new ThreadPoolExecutor(1, 1,
277 <                                   60, TimeUnit.SECONDS,
278 <                                   new ArrayBlockingQueue<Runnable>(10));
279 <
280 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
281 <            public void realRun() throws Exception {
282 <                p.submit(new SmallCallable()).get();
283 <            }});
284 <
285 <        t.start();
286 <        Thread.sleep(SHORT_DELAY_MS);
287 <        t.interrupt();
288 <        t.join();
289 <        joinPool(p);
290 <    }
291 <
292 <    /**
293 <     *  get of submit(callable) throws ExecutionException if callable
294 <     *  throws exception
220 >     * get of submit(callable) throws ExecutionException if callable
221 >     * throws exception
222       */
223      public void testSubmitEE() throws InterruptedException {
224          ThreadPoolExecutor p =
# Line 300 | Line 227 | public class AbstractExecutorServiceTest
227                                     new ArrayBlockingQueue<Runnable>(10));
228  
229          Callable c = new Callable() {
230 <            public Object call() { return 5/0; }};
230 >            public Object call() { throw new ArithmeticException(); }};
231  
232          try {
233              p.submit(c).get();
# Line 314 | Line 241 | public class AbstractExecutorServiceTest
241      /**
242       * invokeAny(null) throws NPE
243       */
244 <    public void testInvokeAny1()
318 <        throws InterruptedException, ExecutionException {
244 >    public void testInvokeAny1() throws Exception {
245          ExecutorService e = new DirectExecutorService();
246          try {
247              e.invokeAny(null);
# Line 329 | Line 255 | public class AbstractExecutorServiceTest
255      /**
256       * invokeAny(empty collection) throws IAE
257       */
258 <    public void testInvokeAny2()
333 <        throws InterruptedException, ExecutionException {
258 >    public void testInvokeAny2() throws Exception {
259          ExecutorService e = new DirectExecutorService();
260          try {
261              e.invokeAny(new ArrayList<Callable<String>>());
# Line 346 | Line 271 | public class AbstractExecutorServiceTest
271       */
272      public void testInvokeAny3() throws Exception {
273          ExecutorService e = new DirectExecutorService();
274 <        List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
275 <        l.add(new Callable<Integer>() {
276 <                  public Integer call() { return 5/0; }});
274 >        List<Callable<Long>> l = new ArrayList<Callable<Long>>();
275 >        l.add(new Callable<Long>() {
276 >            public Long call() { throw new ArithmeticException(); }});
277          l.add(null);
278          try {
279              e.invokeAny(l);
# Line 475 | Line 400 | public class AbstractExecutorServiceTest
400          }
401      }
402  
478
403      /**
404       * timed invokeAny(null) throws NPE
405       */
# Line 525 | Line 449 | public class AbstractExecutorServiceTest
449       */
450      public void testTimedInvokeAny3() throws Exception {
451          ExecutorService e = new DirectExecutorService();
452 <        List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
453 <        l.add(new Callable<Integer>() {
454 <                  public Integer call() { return 5/0; }});
452 >        List<Callable<Long>> l = new ArrayList<Callable<Long>>();
453 >        l.add(new Callable<Long>() {
454 >            public Long call() { throw new ArithmeticException(); }});
455          l.add(null);
456          try {
457              e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
# Line 680 | Line 604 | public class AbstractExecutorServiceTest
604          try {
605              List<Callable<String>> l = new ArrayList<Callable<String>>();
606              l.add(new StringTask());
607 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
607 >            l.add(Executors.callable(possiblyInterruptedRunnable(2 * SHORT_DELAY_MS), TEST_STRING));
608              l.add(new StringTask());
609              List<Future<String>> futures =
610 <                e.invokeAll(l, SMALL_DELAY_MS, MILLISECONDS);
611 <            assertEquals(3, futures.size());
612 <            Iterator<Future<String>> it = futures.iterator();
613 <            Future<String> f1 = it.next();
614 <            Future<String> f2 = it.next();
615 <            Future<String> f3 = it.next();
616 <            assertTrue(f1.isDone());
693 <            assertFalse(f1.isCancelled());
694 <            assertTrue(f2.isDone());
695 <            assertTrue(f3.isDone());
696 <            assertTrue(f3.isCancelled());
610 >                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
611 >            assertEquals(l.size(), futures.size());
612 >            for (Future future : futures)
613 >                assertTrue(future.isDone());
614 >            assertFalse(futures.get(0).isCancelled());
615 >            assertFalse(futures.get(1).isCancelled());
616 >            assertTrue(futures.get(2).isCancelled());
617          } finally {
618              joinPool(e);
619          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines