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.34 by jsr166, Wed Sep 25 07:39:17 2013 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
9   import junit.framework.*;
10   import java.util.*;
11   import java.util.concurrent.*;
12 + import java.util.concurrent.atomic.AtomicBoolean;
13   import static java.util.concurrent.TimeUnit.MILLISECONDS;
14 import java.math.BigInteger;
14   import java.security.*;
15  
16   public class AbstractExecutorServiceTest 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(AbstractExecutorServiceTest.class);
# Line 29 | Line 28 | public class AbstractExecutorServiceTest
28      static class DirectExecutorService extends AbstractExecutorService {
29          public void execute(Runnable r) { r.run(); }
30          public void shutdown() { shutdown = true; }
31 <        public List<Runnable> shutdownNow() { shutdown = true; return Collections.EMPTY_LIST; }
31 >        public List<Runnable> shutdownNow() {
32 >            shutdown = true;
33 >            return Collections.EMPTY_LIST;
34 >        }
35          public boolean isShutdown() { return shutdown; }
36          public boolean isTerminated() { return isShutdown(); }
37 <        public boolean awaitTermination(long timeout, TimeUnit unit) { return isShutdown(); }
37 >        public boolean awaitTermination(long timeout, TimeUnit unit) {
38 >            return isShutdown();
39 >        }
40          private volatile boolean shutdown = false;
41      }
42  
# Line 41 | Line 45 | public class AbstractExecutorServiceTest
45       */
46      public void testExecuteRunnable() throws Exception {
47          ExecutorService e = new DirectExecutorService();
48 <        TrackedShortRunnable task = new TrackedShortRunnable();
49 <        assertFalse(task.done);
50 <        Future<?> future = e.submit(task);
51 <        future.get();
52 <        assertTrue(task.done);
48 >        final AtomicBoolean done = new AtomicBoolean(false);
49 >        Future<?> future = e.submit(new CheckedRunnable() {
50 >            public void realRun() {
51 >                done.set(true);
52 >            }});
53 >        assertNull(future.get());
54 >        assertNull(future.get(0, MILLISECONDS));
55 >        assertTrue(done.get());
56 >        assertTrue(future.isDone());
57 >        assertFalse(future.isCancelled());
58      }
59  
51
60      /**
61       * Completed submit(callable) returns result
62       */
# Line 79 | Line 87 | public class AbstractExecutorServiceTest
87          assertSame(TEST_STRING, result);
88      }
89  
82
90      /**
91 <     * A submitted privileged action to completion
91 >     * A submitted privileged action runs to completion
92       */
93      public void testSubmitPrivilegedAction() throws Exception {
94 <        Policy savedPolicy = null;
95 <        try {
96 <            savedPolicy = Policy.getPolicy();
97 <            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() {
94 >        Runnable r = new CheckedRunnable() {
95 >            public void realRun() throws Exception {
96 >                ExecutorService e = new DirectExecutorService();
97 >                Future future = e.submit(Executors.callable(new PrivilegedAction() {
98                      public Object run() {
99                          return TEST_STRING;
100                      }}));
101  
102 <            Object result = future.get();
103 <            assertSame(TEST_STRING, result);
104 <        }
105 <        finally {
106 <            try {
107 <                Policy.setPolicy(savedPolicy);
108 <            } catch (AccessControlException ok) {
111 <                return;
112 <            }
113 <        }
102 >                assertSame(TEST_STRING, future.get());
103 >            }};
104 >
105 >        runWithPermissions(r,
106 >                           new RuntimePermission("getClassLoader"),
107 >                           new RuntimePermission("setContextClassLoader"),
108 >                           new RuntimePermission("modifyThread"));
109      }
110  
111      /**
112 <     * A submitted a privileged exception action runs to completion
112 >     * A submitted privileged exception action runs to completion
113       */
114      public void testSubmitPrivilegedExceptionAction() throws Exception {
115 <        Policy savedPolicy = null;
116 <        try {
117 <            savedPolicy = Policy.getPolicy();
118 <            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() {
115 >        Runnable r = new CheckedRunnable() {
116 >            public void realRun() throws Exception {
117 >                ExecutorService e = new DirectExecutorService();
118 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
119                      public Object run() {
120                          return TEST_STRING;
121                      }}));
122  
123 <            Object result = future.get();
124 <            assertSame(TEST_STRING, result);
125 <        }
126 <        finally {
142 <            Policy.setPolicy(savedPolicy);
143 <        }
123 >                assertSame(TEST_STRING, future.get());
124 >            }};
125 >
126 >        runWithPermissions(r);
127      }
128  
129      /**
130       * A submitted failed privileged exception action reports exception
131       */
132      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
133 <        Policy savedPolicy = null;
134 <        try {
135 <            savedPolicy = Policy.getPolicy();
136 <            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() {
133 >        Runnable r = new CheckedRunnable() {
134 >            public void realRun() throws Exception {
135 >                ExecutorService e = new DirectExecutorService();
136 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
137                      public Object run() throws Exception {
138                          throw new IndexOutOfBoundsException();
139                      }}));
140  
141 <            future.get();
142 <            shouldThrow();
143 <        } catch (ExecutionException success) {
144 <            assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
145 <        }
146 <        finally {
147 <            Policy.setPolicy(savedPolicy);
148 <        }
141 >                try {
142 >                    future.get();
143 >                    shouldThrow();
144 >                } catch (ExecutionException success) {
145 >                    assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
146 >                }}};
147 >
148 >        runWithPermissions(r);
149      }
150  
151      /**
# Line 186 | Line 159 | public class AbstractExecutorServiceTest
159          } catch (NullPointerException success) {}
160      }
161  
189
162      /**
163       * submit(null callable) throws NPE
164       */
# Line 199 | Line 171 | public class AbstractExecutorServiceTest
171      }
172  
173      /**
174 <     * submit(runnable) throws RejectedExecutionException if
203 <     * executor is saturated.
174 >     * submit(callable).get() throws InterruptedException if interrupted
175       */
176 <    public void testExecute1() {
177 <        ThreadPoolExecutor p =
178 <            new ThreadPoolExecutor(1, 1,
179 <                                   60, TimeUnit.SECONDS,
180 <                                   new ArrayBlockingQueue<Runnable>(1));
181 <        try {
182 <            for (int i = 0; i < 2; ++i)
183 <                p.submit(new MediumRunnable());
184 <            for (int i = 0; i < 2; ++i) {
185 <                try {
186 <                    p.submit(new MediumRunnable());
187 <                    shouldThrow();
188 <                } catch (RejectedExecutionException success) {}
189 <            }
190 <        } finally {
191 <            joinPool(p);
192 <        }
193 <    }
194 <
195 <    /**
196 <     * submit(callable) throws RejectedExecutionException
197 <     * 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 <            }
176 >    public void testInterruptedSubmit() throws InterruptedException {
177 >        final CountDownLatch submitted    = new CountDownLatch(1);
178 >        final CountDownLatch quittingTime = new CountDownLatch(1);
179 >        final ExecutorService p
180 >            = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
181 >                                     new ArrayBlockingQueue<Runnable>(10));
182 >        final Callable<Void> awaiter = new CheckedCallable<Void>() {
183 >            public Void realCall() throws InterruptedException {
184 >                quittingTime.await();
185 >                return null;
186 >            }};
187 >        try {
188 >            Thread t = new Thread(new CheckedInterruptedRunnable() {
189 >                public void realRun() throws Exception {
190 >                    Future<Void> future = p.submit(awaiter);
191 >                    submitted.countDown();
192 >                    future.get();
193 >                }});
194 >            t.start();
195 >            submitted.await();
196 >            t.interrupt();
197 >            t.join();
198          } finally {
199 +            quittingTime.countDown();
200              joinPool(p);
201          }
202      }
203  
247
204      /**
205 <     *  Blocking on submit(callable) throws InterruptedException if
206 <     *  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
205 >     * get of submit(callable) throws ExecutionException if callable
206 >     * throws exception
207       */
208      public void testSubmitEE() throws InterruptedException {
209          ThreadPoolExecutor p =
# Line 300 | Line 212 | public class AbstractExecutorServiceTest
212                                     new ArrayBlockingQueue<Runnable>(10));
213  
214          Callable c = new Callable() {
215 <            public Object call() { return 5/0; }};
215 >            public Object call() { throw new ArithmeticException(); }};
216  
217          try {
218              p.submit(c).get();
# Line 314 | Line 226 | public class AbstractExecutorServiceTest
226      /**
227       * invokeAny(null) throws NPE
228       */
229 <    public void testInvokeAny1()
318 <        throws InterruptedException, ExecutionException {
229 >    public void testInvokeAny1() throws Exception {
230          ExecutorService e = new DirectExecutorService();
231          try {
232              e.invokeAny(null);
# Line 329 | Line 240 | public class AbstractExecutorServiceTest
240      /**
241       * invokeAny(empty collection) throws IAE
242       */
243 <    public void testInvokeAny2()
333 <        throws InterruptedException, ExecutionException {
243 >    public void testInvokeAny2() throws Exception {
244          ExecutorService e = new DirectExecutorService();
245          try {
246              e.invokeAny(new ArrayList<Callable<String>>());
# Line 346 | Line 256 | public class AbstractExecutorServiceTest
256       */
257      public void testInvokeAny3() throws Exception {
258          ExecutorService e = new DirectExecutorService();
259 <        List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
260 <        l.add(new Callable<Integer>() {
261 <                  public Integer call() { return 5/0; }});
259 >        List<Callable<Long>> l = new ArrayList<Callable<Long>>();
260 >        l.add(new Callable<Long>() {
261 >            public Long call() { throw new ArithmeticException(); }});
262          l.add(null);
263          try {
264              e.invokeAny(l);
# Line 475 | Line 385 | public class AbstractExecutorServiceTest
385          }
386      }
387  
478
388      /**
389       * timed invokeAny(null) throws NPE
390       */
# Line 525 | Line 434 | public class AbstractExecutorServiceTest
434       */
435      public void testTimedInvokeAny3() throws Exception {
436          ExecutorService e = new DirectExecutorService();
437 <        List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
438 <        l.add(new Callable<Integer>() {
439 <                  public Integer call() { return 5/0; }});
437 >        List<Callable<Long>> l = new ArrayList<Callable<Long>>();
438 >        l.add(new Callable<Long>() {
439 >            public Long call() { throw new ArithmeticException(); }});
440          l.add(null);
441          try {
442              e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
# Line 680 | Line 589 | public class AbstractExecutorServiceTest
589          try {
590              List<Callable<String>> l = new ArrayList<Callable<String>>();
591              l.add(new StringTask());
592 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
592 >            l.add(Executors.callable(possiblyInterruptedRunnable(2 * SHORT_DELAY_MS), TEST_STRING));
593              l.add(new StringTask());
594              List<Future<String>> futures =
595 <                e.invokeAll(l, SMALL_DELAY_MS, MILLISECONDS);
596 <            assertEquals(3, futures.size());
597 <            Iterator<Future<String>> it = futures.iterator();
598 <            Future<String> f1 = it.next();
599 <            Future<String> f2 = it.next();
600 <            Future<String> f3 = it.next();
601 <            assertTrue(f1.isDone());
693 <            assertFalse(f1.isCancelled());
694 <            assertTrue(f2.isDone());
695 <            assertTrue(f3.isDone());
696 <            assertTrue(f3.isCancelled());
595 >                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
596 >            assertEquals(l.size(), futures.size());
597 >            for (Future future : futures)
598 >                assertTrue(future.isDone());
599 >            assertFalse(futures.get(0).isCancelled());
600 >            assertFalse(futures.get(1).isCancelled());
601 >            assertTrue(futures.get(2).isCancelled());
602          } finally {
603              joinPool(e);
604          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines