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.32 by jsr166, Sun May 29 07:01:17 2011 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);
48 >        final AtomicBoolean done = new AtomicBoolean(false);
49 >        CheckedRunnable task = new CheckedRunnable() {
50 >            public void realRun() {
51 >                done.set(true);
52 >            }};
53          Future<?> future = e.submit(task);
54 <        future.get();
55 <        assertTrue(task.done);
54 >        assertNull(future.get());
55 >        assertNull(future.get(0, MILLISECONDS));
56 >        assertTrue(done.get());
57 >        assertTrue(future.isDone());
58 >        assertFalse(future.isCancelled());
59      }
60  
51
61      /**
62       * Completed submit(callable) returns result
63       */
# Line 79 | Line 88 | public class AbstractExecutorServiceTest
88          assertSame(TEST_STRING, result);
89      }
90  
82
91      /**
92 <     * A submitted privileged action to completion
92 >     * A submitted privileged action runs to completion
93       */
94      public void testSubmitPrivilegedAction() throws Exception {
95 <        Policy savedPolicy = null;
96 <        try {
97 <            savedPolicy = Policy.getPolicy();
98 <            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() {
95 >        Runnable r = new CheckedRunnable() {
96 >            public void realRun() throws Exception {
97 >                ExecutorService e = new DirectExecutorService();
98 >                Future future = e.submit(Executors.callable(new PrivilegedAction() {
99                      public Object run() {
100                          return TEST_STRING;
101                      }}));
102  
103 <            Object result = future.get();
104 <            assertSame(TEST_STRING, result);
105 <        }
106 <        finally {
107 <            try {
108 <                Policy.setPolicy(savedPolicy);
109 <            } catch (AccessControlException ok) {
111 <                return;
112 <            }
113 <        }
103 >                assertSame(TEST_STRING, future.get());
104 >            }};
105 >
106 >        runWithPermissions(r,
107 >                           new RuntimePermission("getClassLoader"),
108 >                           new RuntimePermission("setContextClassLoader"),
109 >                           new RuntimePermission("modifyThread"));
110      }
111  
112      /**
113 <     * A submitted a privileged exception action runs to completion
113 >     * A submitted privileged exception action runs to completion
114       */
115      public void testSubmitPrivilegedExceptionAction() throws Exception {
116 <        Policy savedPolicy = null;
117 <        try {
118 <            savedPolicy = Policy.getPolicy();
119 <            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() {
116 >        Runnable r = new CheckedRunnable() {
117 >            public void realRun() throws Exception {
118 >                ExecutorService e = new DirectExecutorService();
119 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
120                      public Object run() {
121                          return TEST_STRING;
122                      }}));
123  
124 <            Object result = future.get();
125 <            assertSame(TEST_STRING, result);
126 <        }
127 <        finally {
142 <            Policy.setPolicy(savedPolicy);
143 <        }
124 >                assertSame(TEST_STRING, future.get());
125 >            }};
126 >
127 >        runWithPermissions(r);
128      }
129  
130      /**
131       * A submitted failed privileged exception action reports exception
132       */
133      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
134 <        Policy savedPolicy = null;
135 <        try {
136 <            savedPolicy = Policy.getPolicy();
137 <            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() {
134 >        Runnable r = new CheckedRunnable() {
135 >            public void realRun() throws Exception {
136 >                ExecutorService e = new DirectExecutorService();
137 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
138                      public Object run() throws Exception {
139                          throw new IndexOutOfBoundsException();
140                      }}));
141  
142 <            future.get();
143 <            shouldThrow();
144 <        } catch (ExecutionException success) {
145 <            assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
146 <        }
147 <        finally {
148 <            Policy.setPolicy(savedPolicy);
149 <        }
142 >                try {
143 >                    future.get();
144 >                    shouldThrow();
145 >                } catch (ExecutionException success) {
146 >                    assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
147 >                }}};
148 >
149 >        runWithPermissions(r);
150      }
151  
152      /**
# Line 186 | Line 160 | public class AbstractExecutorServiceTest
160          } catch (NullPointerException success) {}
161      }
162  
189
163      /**
164       * submit(null callable) throws NPE
165       */
# Line 199 | Line 172 | public class AbstractExecutorServiceTest
172      }
173  
174      /**
175 <     * submit(runnable) throws RejectedExecutionException if
203 <     * executor is saturated.
204 <     */
205 <    public void testExecute1() {
206 <        ThreadPoolExecutor p =
207 <            new ThreadPoolExecutor(1, 1,
208 <                                   60, TimeUnit.SECONDS,
209 <                                   new ArrayBlockingQueue<Runnable>(1));
210 <        try {
211 <            for (int i = 0; i < 2; ++i)
212 <                p.submit(new MediumRunnable());
213 <            for (int i = 0; i < 2; ++i) {
214 <                try {
215 <                    p.submit(new MediumRunnable());
216 <                    shouldThrow();
217 <                } catch (RejectedExecutionException success) {}
218 <            }
219 <        } finally {
220 <            joinPool(p);
221 <        }
222 <    }
223 <
224 <    /**
225 <     * submit(callable) throws RejectedExecutionException
226 <     * if executor is saturated.
175 >     * submit(callable).get() throws InterruptedException if interrupted
176       */
177 <    public void testExecute2() {
178 <        ThreadPoolExecutor p =
179 <            new ThreadPoolExecutor(1, 1,
180 <                                   60, TimeUnit.SECONDS,
181 <                                   new ArrayBlockingQueue<Runnable>(1));
182 <        try {
183 <            for (int i = 0; i < 2; ++i)
184 <                p.submit(new MediumRunnable());
185 <            for (int i = 0; i < 2; ++i) {
186 <                try {
187 <                    p.submit(new SmallCallable());
188 <                    shouldThrow();
189 <                } catch (RejectedExecutionException success) {}
190 <            }
177 >    public void testInterruptedSubmit() throws InterruptedException {
178 >        final CountDownLatch submitted    = new CountDownLatch(1);
179 >        final CountDownLatch quittingTime = new CountDownLatch(1);
180 >        final ExecutorService p
181 >            = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
182 >                                     new ArrayBlockingQueue<Runnable>(10));
183 >        final Callable<Void> awaiter = new CheckedCallable<Void>() {
184 >            public Void realCall() throws InterruptedException {
185 >                quittingTime.await();
186 >                return null;
187 >            }};
188 >        try {
189 >            Thread t = new Thread(new CheckedInterruptedRunnable() {
190 >                public void realRun() throws Exception {
191 >                    Future<Void> future = p.submit(awaiter);
192 >                    submitted.countDown();
193 >                    future.get();
194 >                }});
195 >            t.start();
196 >            submitted.await();
197 >            t.interrupt();
198 >            t.join();
199          } finally {
200 +            quittingTime.countDown();
201              joinPool(p);
202          }
203      }
204  
247
205      /**
206 <     *  Blocking on submit(callable) throws InterruptedException if
207 <     *  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
206 >     * get of submit(callable) throws ExecutionException if callable
207 >     * throws exception
208       */
209      public void testSubmitEE() throws InterruptedException {
210          ThreadPoolExecutor p =
# Line 314 | Line 227 | public class AbstractExecutorServiceTest
227      /**
228       * invokeAny(null) throws NPE
229       */
230 <    public void testInvokeAny1()
318 <        throws InterruptedException, ExecutionException {
230 >    public void testInvokeAny1() throws Exception {
231          ExecutorService e = new DirectExecutorService();
232          try {
233              e.invokeAny(null);
# Line 329 | Line 241 | public class AbstractExecutorServiceTest
241      /**
242       * invokeAny(empty collection) throws IAE
243       */
244 <    public void testInvokeAny2()
333 <        throws InterruptedException, ExecutionException {
244 >    public void testInvokeAny2() throws Exception {
245          ExecutorService e = new DirectExecutorService();
246          try {
247              e.invokeAny(new ArrayList<Callable<String>>());
# Line 475 | Line 386 | public class AbstractExecutorServiceTest
386          }
387      }
388  
478
389      /**
390       * timed invokeAny(null) throws NPE
391       */
# Line 680 | Line 590 | public class AbstractExecutorServiceTest
590          try {
591              List<Callable<String>> l = new ArrayList<Callable<String>>();
592              l.add(new StringTask());
593 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
593 >            l.add(Executors.callable(possiblyInterruptedRunnable(2 * SHORT_DELAY_MS), TEST_STRING));
594              l.add(new StringTask());
595              List<Future<String>> futures =
596 <                e.invokeAll(l, SMALL_DELAY_MS, MILLISECONDS);
597 <            assertEquals(3, futures.size());
598 <            Iterator<Future<String>> it = futures.iterator();
599 <            Future<String> f1 = it.next();
600 <            Future<String> f2 = it.next();
601 <            Future<String> f3 = it.next();
602 <            assertTrue(f1.isDone());
693 <            assertFalse(f1.isCancelled());
694 <            assertTrue(f2.isDone());
695 <            assertTrue(f3.isDone());
696 <            assertTrue(f3.isCancelled());
596 >                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
597 >            assertEquals(l.size(), futures.size());
598 >            for (Future future : futures)
599 >                assertTrue(future.isDone());
600 >            assertFalse(futures.get(0).isCancelled());
601 >            assertFalse(futures.get(1).isCancelled());
602 >            assertTrue(futures.get(2).isCancelled());
603          } finally {
604              joinPool(e);
605          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines