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.19 by jsr166, Fri Nov 20 05:25:10 2009 UTC vs.
Revision 1.47 by jsr166, Sun Jul 16 18:05:47 2017 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 + 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.PrivilegedAction;
12 > import java.security.PrivilegedExceptionAction;
13 > import java.util.ArrayList;
14 > import java.util.Collection;
15 > import java.util.Collections;
16 > import java.util.List;
17 > import java.util.concurrent.AbstractExecutorService;
18 > import java.util.concurrent.ArrayBlockingQueue;
19 > import java.util.concurrent.Callable;
20 > import java.util.concurrent.CancellationException;
21 > import java.util.concurrent.CountDownLatch;
22 > import java.util.concurrent.ExecutionException;
23 > import java.util.concurrent.Executors;
24 > import java.util.concurrent.ExecutorService;
25 > import java.util.concurrent.Future;
26 > import java.util.concurrent.ThreadPoolExecutor;
27 > import java.util.concurrent.TimeUnit;
28 > import java.util.concurrent.atomic.AtomicBoolean;
29 >
30 > import junit.framework.Test;
31 > import junit.framework.TestSuite;
32  
33   public class AbstractExecutorServiceTest extends JSR166TestCase {
34      public static void main(String[] args) {
35 <        junit.textui.TestRunner.run (suite());
35 >        main(suite(), args);
36      }
37      public static Test suite() {
38          return new TestSuite(AbstractExecutorServiceTest.class);
# Line 28 | Line 45 | public class AbstractExecutorServiceTest
45      static class DirectExecutorService extends AbstractExecutorService {
46          public void execute(Runnable r) { r.run(); }
47          public void shutdown() { shutdown = true; }
48 <        public List<Runnable> shutdownNow() { shutdown = true; return Collections.EMPTY_LIST; }
48 >        public List<Runnable> shutdownNow() {
49 >            shutdown = true;
50 >            return Collections.EMPTY_LIST;
51 >        }
52          public boolean isShutdown() { return shutdown; }
53          public boolean isTerminated() { return isShutdown(); }
54 <        public boolean awaitTermination(long timeout, TimeUnit unit) { return isShutdown(); }
54 >        public boolean awaitTermination(long timeout, TimeUnit unit) {
55 >            return isShutdown();
56 >        }
57          private volatile boolean shutdown = false;
58      }
59  
# Line 40 | Line 62 | public class AbstractExecutorServiceTest
62       */
63      public void testExecuteRunnable() throws Exception {
64          ExecutorService e = new DirectExecutorService();
65 <        TrackedShortRunnable task = new TrackedShortRunnable();
66 <        assertFalse(task.done);
67 <        Future<?> future = e.submit(task);
68 <        future.get();
69 <        assertTrue(task.done);
65 >        final AtomicBoolean done = new AtomicBoolean(false);
66 >        Future<?> future = e.submit(new CheckedRunnable() {
67 >            public void realRun() {
68 >                done.set(true);
69 >            }});
70 >        assertNull(future.get());
71 >        assertNull(future.get(0, MILLISECONDS));
72 >        assertTrue(done.get());
73 >        assertTrue(future.isDone());
74 >        assertFalse(future.isCancelled());
75      }
76  
50
77      /**
78       * Completed submit(callable) returns result
79       */
# Line 78 | Line 104 | public class AbstractExecutorServiceTest
104          assertSame(TEST_STRING, result);
105      }
106  
81
107      /**
108 <     * A submitted privileged action to completion
108 >     * A submitted privileged action runs to completion
109       */
110      public void testSubmitPrivilegedAction() throws Exception {
111 <        Policy savedPolicy = null;
112 <        try {
113 <            savedPolicy = Policy.getPolicy();
114 <            AdjustablePolicy policy = new AdjustablePolicy();
90 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
91 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
92 <            Policy.setPolicy(policy);
93 <        } catch (AccessControlException ok) {
94 <            return;
95 <        }
96 <        try {
97 <            ExecutorService e = new DirectExecutorService();
98 <            Future future = e.submit(Executors.callable(new PrivilegedAction() {
111 >        Runnable r = new CheckedRunnable() {
112 >            public void realRun() throws Exception {
113 >                ExecutorService e = new DirectExecutorService();
114 >                Future future = e.submit(Executors.callable(new PrivilegedAction() {
115                      public Object run() {
116                          return TEST_STRING;
117                      }}));
118  
119 <            Object result = future.get();
120 <            assertSame(TEST_STRING, result);
121 <        }
122 <        finally {
123 <            try {
124 <                Policy.setPolicy(savedPolicy);
125 <            } catch (AccessControlException ok) {
110 <                return;
111 <            }
112 <        }
119 >                assertSame(TEST_STRING, future.get());
120 >            }};
121 >
122 >        runWithPermissions(r,
123 >                           new RuntimePermission("getClassLoader"),
124 >                           new RuntimePermission("setContextClassLoader"),
125 >                           new RuntimePermission("modifyThread"));
126      }
127  
128      /**
129 <     * A submitted a privileged exception action runs to completion
129 >     * A submitted privileged exception action runs to completion
130       */
131      public void testSubmitPrivilegedExceptionAction() throws Exception {
132 <        Policy savedPolicy = null;
133 <        try {
134 <            savedPolicy = Policy.getPolicy();
135 <            AdjustablePolicy policy = new AdjustablePolicy();
123 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
124 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
125 <            Policy.setPolicy(policy);
126 <        } catch (AccessControlException ok) {
127 <            return;
128 <        }
129 <
130 <        try {
131 <            ExecutorService e = new DirectExecutorService();
132 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
132 >        Runnable r = new CheckedRunnable() {
133 >            public void realRun() throws Exception {
134 >                ExecutorService e = new DirectExecutorService();
135 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
136                      public Object run() {
137                          return TEST_STRING;
138                      }}));
139  
140 <            Object result = future.get();
141 <            assertSame(TEST_STRING, result);
142 <        }
143 <        finally {
141 <            Policy.setPolicy(savedPolicy);
142 <        }
140 >                assertSame(TEST_STRING, future.get());
141 >            }};
142 >
143 >        runWithPermissions(r);
144      }
145  
146      /**
147       * A submitted failed privileged exception action reports exception
148       */
149      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
150 <        Policy savedPolicy = null;
151 <        try {
152 <            savedPolicy = Policy.getPolicy();
153 <            AdjustablePolicy policy = new AdjustablePolicy();
153 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
154 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
155 <            Policy.setPolicy(policy);
156 <        } catch (AccessControlException ok) {
157 <            return;
158 <        }
159 <
160 <        try {
161 <            ExecutorService e = new DirectExecutorService();
162 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
150 >        Runnable r = new CheckedRunnable() {
151 >            public void realRun() throws Exception {
152 >                ExecutorService e = new DirectExecutorService();
153 >                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
154                      public Object run() throws Exception {
155                          throw new IndexOutOfBoundsException();
156                      }}));
157  
167            future.get();
168            shouldThrow();
169        } catch (ExecutionException success) {
170            assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
171        }
172        finally {
173            Policy.setPolicy(savedPolicy);
174        }
175    }
176
177    /**
178     * execute(null runnable) throws NPE
179     */
180    public void testExecuteNullRunnable() {
181        try {
182            ExecutorService e = new DirectExecutorService();
183            e.submit((Runnable) null);
184            shouldThrow();
185        } catch (NullPointerException success) {}
186    }
187
188
189    /**
190     * submit(null callable) throws NPE
191     */
192    public void testSubmitNullCallable() {
193        try {
194            ExecutorService e = new DirectExecutorService();
195            e.submit((Callable) null);
196            shouldThrow();
197        } catch (NullPointerException success) {}
198    }
199
200    /**
201     * submit(runnable) throws RejectedExecutionException if
202     * executor is saturated.
203     */
204    public void testExecute1() {
205        ThreadPoolExecutor p =
206            new ThreadPoolExecutor(1, 1,
207                                   60, TimeUnit.SECONDS,
208                                   new ArrayBlockingQueue<Runnable>(1));
209        try {
210            for (int i = 0; i < 2; ++i)
211                p.submit(new MediumRunnable());
212            for (int i = 0; i < 2; ++i) {
158                  try {
159 <                    p.submit(new MediumRunnable());
159 >                    future.get();
160                      shouldThrow();
161 <                } catch (RejectedExecutionException success) {}
162 <            }
163 <        } finally {
164 <            joinPool(p);
165 <        }
161 >                } catch (ExecutionException success) {
162 >                    assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
163 >                }}};
164 >
165 >        runWithPermissions(r);
166      }
167  
168      /**
169 <     * submit(callable) throws RejectedExecutionException
225 <     * if executor is saturated.
169 >     * Submitting null tasks throws NullPointerException.
170       */
171 <    public void testExecute2() {
172 <        ThreadPoolExecutor p =
173 <            new ThreadPoolExecutor(1, 1,
174 <                                   60, TimeUnit.SECONDS,
175 <                                   new ArrayBlockingQueue<Runnable>(1));
176 <        try {
177 <            for (int i = 0; i < 2; ++i)
178 <                p.submit(new MediumRunnable());
179 <            for (int i = 0; i < 2; ++i) {
180 <                try {
181 <                    p.submit(new SmallCallable());
182 <                    shouldThrow();
183 <                } catch (RejectedExecutionException success) {}
184 <            }
185 <        } finally {
186 <            joinPool(p);
171 >    @SuppressWarnings("FutureReturnValueIgnored")
172 >    public void testNullTaskSubmission() throws Exception {
173 >        final ExecutorService e = new DirectExecutorService();
174 >        try (PoolCleaner cleaner = cleaner(e)) {
175 >            try {
176 >                e.execute((Runnable) null);
177 >                shouldThrow();
178 >            } catch (NullPointerException success) {}
179 >            try {
180 >                e.submit((Runnable) null);
181 >                shouldThrow();
182 >            } catch (NullPointerException success) {}
183 >            try {
184 >                e.submit((Callable) null);
185 >                shouldThrow();
186 >            } catch (NullPointerException success) {}
187          }
188      }
189  
246
190      /**
191 <     *  Blocking on submit(callable) throws InterruptedException if
249 <     *  caller interrupted.
191 >     * submit(callable).get() throws InterruptedException if interrupted
192       */
193      public void testInterruptedSubmit() throws InterruptedException {
194 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
195 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
196 <            public void realRun() throws Exception {
197 <                p.submit(new CheckedCallable<Object>() {
198 <                             public Object realCall()
199 <                                 throws InterruptedException {
200 <                                 Thread.sleep(SMALL_DELAY_MS);
201 <                                 return null;
202 <                             }}).get();
203 <            }});
204 <
205 <        t.start();
206 <        Thread.sleep(SHORT_DELAY_MS);
207 <        t.interrupt();
208 <        joinPool(p);
209 <    }
210 <
269 <    /**
270 <     *  get of submitted callable throws InterruptedException if callable
271 <     *  interrupted
272 <     */
273 <    public void testSubmitIE() throws InterruptedException {
274 <        final ThreadPoolExecutor p =
275 <            new ThreadPoolExecutor(1, 1,
276 <                                   60, TimeUnit.SECONDS,
277 <                                   new ArrayBlockingQueue<Runnable>(10));
278 <
279 <        Thread t = new Thread(new CheckedInterruptedRunnable() {
280 <            public void realRun() throws Exception {
281 <                p.submit(new SmallCallable()).get();
282 <            }});
194 >        final CountDownLatch submitted    = new CountDownLatch(1);
195 >        final CountDownLatch quittingTime = new CountDownLatch(1);
196 >        final Callable<Void> awaiter = new CheckedCallable<Void>() {
197 >            public Void realCall() throws InterruptedException {
198 >                assertTrue(quittingTime.await(2*LONG_DELAY_MS, MILLISECONDS));
199 >                return null;
200 >            }};
201 >        final ExecutorService p
202 >            = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
203 >                                     new ArrayBlockingQueue<Runnable>(10));
204 >        try (PoolCleaner cleaner = cleaner(p, quittingTime)) {
205 >            Thread t = newStartedThread(new CheckedInterruptedRunnable() {
206 >                public void realRun() throws Exception {
207 >                    Future<Void> future = p.submit(awaiter);
208 >                    submitted.countDown();
209 >                    future.get();
210 >                }});
211  
212 <        t.start();
213 <        Thread.sleep(SHORT_DELAY_MS);
214 <        t.interrupt();
215 <        t.join();
288 <        joinPool(p);
212 >            await(submitted);
213 >            t.interrupt();
214 >            awaitTermination(t);
215 >        }
216      }
217  
218      /**
219 <     *  get of submit(callable) throws ExecutionException if callable
220 <     *  throws exception
219 >     * get of submit(callable) throws ExecutionException if callable
220 >     * throws exception
221       */
222      public void testSubmitEE() throws InterruptedException {
223 <        ThreadPoolExecutor p =
223 >        final ThreadPoolExecutor p =
224              new ThreadPoolExecutor(1, 1,
225                                     60, TimeUnit.SECONDS,
226                                     new ArrayBlockingQueue<Runnable>(10));
227 <
228 <        Callable c = new Callable() {
229 <            public Object call() { return 5/0; }};
230 <
231 <        try {
232 <            p.submit(c).get();
233 <            shouldThrow();
234 <        } catch (ExecutionException success) {
235 <            assertTrue(success.getCause() instanceof ArithmeticException);
227 >        try (PoolCleaner cleaner = cleaner(p)) {
228 >            Callable c = new Callable() {
229 >                public Object call() { throw new ArithmeticException(); }};
230 >            try {
231 >                p.submit(c).get();
232 >                shouldThrow();
233 >            } catch (ExecutionException success) {
234 >                assertTrue(success.getCause() instanceof ArithmeticException);
235 >            }
236          }
310        joinPool(p);
237      }
238  
239      /**
240       * invokeAny(null) throws NPE
241       */
242 <    public void testInvokeAny1()
243 <        throws InterruptedException, ExecutionException {
244 <        ExecutorService e = new DirectExecutorService();
245 <        try {
246 <            e.invokeAny(null);
247 <            shouldThrow();
248 <        } catch (NullPointerException success) {
323 <        } finally {
324 <            joinPool(e);
242 >    public void testInvokeAny1() throws Exception {
243 >        final ExecutorService e = new DirectExecutorService();
244 >        try (PoolCleaner cleaner = cleaner(e)) {
245 >            try {
246 >                e.invokeAny(null);
247 >                shouldThrow();
248 >            } catch (NullPointerException success) {}
249          }
250      }
251  
252      /**
253 <     * invokeAny(empty collection) throws IAE
253 >     * invokeAny(empty collection) throws IllegalArgumentException
254       */
255 <    public void testInvokeAny2()
256 <        throws InterruptedException, ExecutionException {
257 <        ExecutorService e = new DirectExecutorService();
258 <        try {
259 <            e.invokeAny(new ArrayList<Callable<String>>());
260 <            shouldThrow();
261 <        } catch (IllegalArgumentException success) {
262 <        } finally {
263 <            joinPool(e);
255 >    public void testInvokeAny2() throws Exception {
256 >        final ExecutorService e = new DirectExecutorService();
257 >        final Collection<Callable<String>> emptyCollection
258 >            = Collections.emptyList();
259 >        try (PoolCleaner cleaner = cleaner(e)) {
260 >            try {
261 >                e.invokeAny(emptyCollection);
262 >                shouldThrow();
263 >            } catch (IllegalArgumentException success) {}
264          }
265      }
266  
# Line 344 | Line 268 | public class AbstractExecutorServiceTest
268       * invokeAny(c) throws NPE if c has null elements
269       */
270      public void testInvokeAny3() throws Exception {
271 <        final CountDownLatch latch = new CountDownLatch(1);
272 <        ExecutorService e = new DirectExecutorService();
273 <        try {
274 <            ArrayList<Callable<Integer>> l
275 <                = new ArrayList<Callable<Integer>>();
352 <            l.add(new Callable<Integer>() {
353 <                      public Integer call() { return 5/0; }});
271 >        final ExecutorService e = new DirectExecutorService();
272 >        try (PoolCleaner cleaner = cleaner(e)) {
273 >            List<Callable<Long>> l = new ArrayList<>();
274 >            l.add(new Callable<Long>() {
275 >                      public Long call() { throw new ArithmeticException(); }});
276              l.add(null);
277 <            e.invokeAny(l);
278 <            shouldThrow();
279 <        } catch (NullPointerException success) {
280 <        } finally {
359 <            latch.countDown();
360 <            joinPool(e);
277 >            try {
278 >                e.invokeAny(l);
279 >                shouldThrow();
280 >            } catch (NullPointerException success) {}
281          }
282      }
283  
# Line 365 | Line 285 | public class AbstractExecutorServiceTest
285       * invokeAny(c) throws ExecutionException if no task in c completes
286       */
287      public void testInvokeAny4() throws InterruptedException {
288 <        ExecutorService e = new DirectExecutorService();
289 <        try {
290 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
288 >        final ExecutorService e = new DirectExecutorService();
289 >        try (PoolCleaner cleaner = cleaner(e)) {
290 >            List<Callable<String>> l = new ArrayList<>();
291              l.add(new NPETask());
292 <            e.invokeAny(l);
293 <            shouldThrow();
294 <        } catch (ExecutionException success) {
295 <            assertTrue(success.getCause() instanceof NullPointerException);
296 <        } finally {
297 <            joinPool(e);
292 >            try {
293 >                e.invokeAny(l);
294 >                shouldThrow();
295 >            } catch (ExecutionException success) {
296 >                assertTrue(success.getCause() instanceof NullPointerException);
297 >            }
298          }
299      }
300  
# Line 382 | Line 302 | public class AbstractExecutorServiceTest
302       * invokeAny(c) returns result of some task in c if at least one completes
303       */
304      public void testInvokeAny5() throws Exception {
305 <        ExecutorService e = new DirectExecutorService();
306 <        try {
307 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
305 >        final ExecutorService e = new DirectExecutorService();
306 >        try (PoolCleaner cleaner = cleaner(e)) {
307 >            List<Callable<String>> l = new ArrayList<>();
308              l.add(new StringTask());
309              l.add(new StringTask());
310              String result = e.invokeAny(l);
311              assertSame(TEST_STRING, result);
392        } finally {
393            joinPool(e);
312          }
313      }
314  
# Line 398 | Line 316 | public class AbstractExecutorServiceTest
316       * invokeAll(null) throws NPE
317       */
318      public void testInvokeAll1() throws InterruptedException {
319 <        ExecutorService e = new DirectExecutorService();
320 <        try {
321 <            e.invokeAll(null);
322 <            shouldThrow();
323 <        } catch (NullPointerException success) {
324 <        } finally {
407 <            joinPool(e);
319 >        final ExecutorService e = new DirectExecutorService();
320 >        try (PoolCleaner cleaner = cleaner(e)) {
321 >            try {
322 >                e.invokeAll(null);
323 >                shouldThrow();
324 >            } catch (NullPointerException success) {}
325          }
326      }
327  
328      /**
329 <     * invokeAll(empty collection) returns empty collection
329 >     * invokeAll(empty collection) returns empty list
330       */
331      public void testInvokeAll2() throws InterruptedException {
332 <        ExecutorService e = new DirectExecutorService();
333 <        try {
334 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
332 >        final ExecutorService e = new DirectExecutorService();
333 >        final Collection<Callable<String>> emptyCollection
334 >            = Collections.emptyList();
335 >        try (PoolCleaner cleaner = cleaner(e)) {
336 >            List<Future<String>> r = e.invokeAll(emptyCollection);
337              assertTrue(r.isEmpty());
419        } finally {
420            joinPool(e);
338          }
339      }
340  
# Line 425 | Line 342 | public class AbstractExecutorServiceTest
342       * invokeAll(c) throws NPE if c has null elements
343       */
344      public void testInvokeAll3() throws InterruptedException {
345 <        ExecutorService e = new DirectExecutorService();
346 <        try {
347 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
345 >        final ExecutorService e = new DirectExecutorService();
346 >        try (PoolCleaner cleaner = cleaner(e)) {
347 >            List<Callable<String>> l = new ArrayList<>();
348              l.add(new StringTask());
349              l.add(null);
350 <            e.invokeAll(l);
351 <            shouldThrow();
352 <        } catch (NullPointerException success) {
353 <        } finally {
437 <            joinPool(e);
350 >            try {
351 >                e.invokeAll(l);
352 >                shouldThrow();
353 >            } catch (NullPointerException success) {}
354          }
355      }
356  
# Line 442 | Line 358 | public class AbstractExecutorServiceTest
358       * get of returned element of invokeAll(c) throws exception on failed task
359       */
360      public void testInvokeAll4() throws Exception {
361 <        ExecutorService e = new DirectExecutorService();
362 <        try {
363 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
361 >        final ExecutorService e = new DirectExecutorService();
362 >        try (PoolCleaner cleaner = cleaner(e)) {
363 >            List<Callable<String>> l = new ArrayList<>();
364              l.add(new NPETask());
365 <            List<Future<String>> result = e.invokeAll(l);
366 <            assertEquals(1, result.size());
367 <            for (Future<String> future : result) {
368 <                try {
369 <                    future.get();
370 <                    shouldThrow();
371 <                } catch (ExecutionException success) {
456 <                    Throwable cause = success.getCause();
457 <                    assertTrue(cause instanceof NullPointerException);
458 <                }
365 >            List<Future<String>> futures = e.invokeAll(l);
366 >            assertEquals(1, futures.size());
367 >            try {
368 >                futures.get(0).get();
369 >                shouldThrow();
370 >            } catch (ExecutionException success) {
371 >                assertTrue(success.getCause() instanceof NullPointerException);
372              }
460        } finally {
461            joinPool(e);
373          }
374      }
375  
# Line 466 | Line 377 | public class AbstractExecutorServiceTest
377       * invokeAll(c) returns results of all completed tasks in c
378       */
379      public void testInvokeAll5() throws Exception {
380 <        ExecutorService e = new DirectExecutorService();
381 <        try {
382 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
380 >        final ExecutorService e = new DirectExecutorService();
381 >        try (PoolCleaner cleaner = cleaner(e)) {
382 >            List<Callable<String>> l = new ArrayList<>();
383              l.add(new StringTask());
384              l.add(new StringTask());
385 <            List<Future<String>> result = e.invokeAll(l);
386 <            assertEquals(2, result.size());
387 <            for (Future<String> future : result)
385 >            List<Future<String>> futures = e.invokeAll(l);
386 >            assertEquals(2, futures.size());
387 >            for (Future<String> future : futures)
388                  assertSame(TEST_STRING, future.get());
478        } finally {
479            joinPool(e);
389          }
390      }
391  
483
392      /**
393       * timed invokeAny(null) throws NPE
394       */
395      public void testTimedInvokeAny1() throws Exception {
396 <        ExecutorService e = new DirectExecutorService();
397 <        try {
398 <            e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
399 <            shouldThrow();
400 <        } catch (NullPointerException success) {
401 <        } finally {
494 <            joinPool(e);
396 >        final ExecutorService e = new DirectExecutorService();
397 >        try (PoolCleaner cleaner = cleaner(e)) {
398 >            try {
399 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
400 >                shouldThrow();
401 >            } catch (NullPointerException success) {}
402          }
403      }
404  
405      /**
406 <     * timed invokeAny(null time unit) throws NPE
406 >     * timed invokeAny(null time unit) throws NullPointerException
407       */
408      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
409 <        ExecutorService e = new DirectExecutorService();
410 <        try {
411 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
409 >        final ExecutorService e = new DirectExecutorService();
410 >        try (PoolCleaner cleaner = cleaner(e)) {
411 >            List<Callable<String>> l = new ArrayList<>();
412              l.add(new StringTask());
413 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
414 <            shouldThrow();
415 <        } catch (NullPointerException success) {
416 <        } finally {
510 <            joinPool(e);
413 >            try {
414 >                e.invokeAny(l, randomTimeout(), null);
415 >                shouldThrow();
416 >            } catch (NullPointerException success) {}
417          }
418      }
419  
420      /**
421 <     * timed invokeAny(empty collection) throws IAE
421 >     * timed invokeAny(empty collection) throws IllegalArgumentException
422       */
423      public void testTimedInvokeAny2() throws Exception {
424 <        ExecutorService e = new DirectExecutorService();
425 <        try {
426 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
427 <            shouldThrow();
428 <        } catch (IllegalArgumentException success) {
429 <        } finally {
430 <            joinPool(e);
424 >        final ExecutorService e = new DirectExecutorService();
425 >        final Collection<Callable<String>> emptyCollection
426 >            = Collections.emptyList();
427 >        try (PoolCleaner cleaner = cleaner(e)) {
428 >            try {
429 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
430 >                shouldThrow();
431 >            } catch (IllegalArgumentException success) {}
432          }
433      }
434  
# Line 529 | Line 436 | public class AbstractExecutorServiceTest
436       * timed invokeAny(c) throws NPE if c has null elements
437       */
438      public void testTimedInvokeAny3() throws Exception {
439 <        final CountDownLatch latch = new CountDownLatch(1);
440 <        ExecutorService e = new DirectExecutorService();
441 <        try {
442 <            ArrayList<Callable<Integer>> l
443 <                = new ArrayList<Callable<Integer>>();
537 <            l.add(new Callable<Integer>() {
538 <                      public Integer call() { return 5/0; }});
439 >        final ExecutorService e = new DirectExecutorService();
440 >        try (PoolCleaner cleaner = cleaner(e)) {
441 >            List<Callable<Long>> l = new ArrayList<>();
442 >            l.add(new Callable<Long>() {
443 >                      public Long call() { throw new ArithmeticException(); }});
444              l.add(null);
445 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
446 <            shouldThrow();
447 <        } catch (NullPointerException success) {
448 <        } finally {
544 <            latch.countDown();
545 <            joinPool(e);
445 >            try {
446 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
447 >                shouldThrow();
448 >            } catch (NullPointerException success) {}
449          }
450      }
451  
# Line 550 | Line 453 | public class AbstractExecutorServiceTest
453       * timed invokeAny(c) throws ExecutionException if no task completes
454       */
455      public void testTimedInvokeAny4() throws Exception {
456 <        ExecutorService e = new DirectExecutorService();
457 <        try {
458 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
456 >        final ExecutorService e = new DirectExecutorService();
457 >        try (PoolCleaner cleaner = cleaner(e)) {
458 >            long startTime = System.nanoTime();
459 >            List<Callable<String>> l = new ArrayList<>();
460              l.add(new NPETask());
461 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
462 <            shouldThrow();
463 <        } catch (ExecutionException success) {
464 <            assertTrue(success.getCause() instanceof NullPointerException);
465 <        } finally {
466 <            joinPool(e);
461 >            try {
462 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
463 >                shouldThrow();
464 >            } catch (ExecutionException success) {
465 >                assertTrue(success.getCause() instanceof NullPointerException);
466 >            }
467 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
468          }
469      }
470  
# Line 567 | Line 472 | public class AbstractExecutorServiceTest
472       * timed invokeAny(c) returns result of some task in c
473       */
474      public void testTimedInvokeAny5() throws Exception {
475 <        ExecutorService e = new DirectExecutorService();
476 <        try {
477 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
475 >        final ExecutorService e = new DirectExecutorService();
476 >        try (PoolCleaner cleaner = cleaner(e)) {
477 >            long startTime = System.nanoTime();
478 >            List<Callable<String>> l = new ArrayList<>();
479              l.add(new StringTask());
480              l.add(new StringTask());
481 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
481 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
482              assertSame(TEST_STRING, result);
483 <        } finally {
578 <            joinPool(e);
483 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
484          }
485      }
486  
487      /**
488 <     * timed invokeAll(null) throws NPE
488 >     * timed invokeAll(null) throws NullPointerException
489       */
490      public void testTimedInvokeAll1() throws InterruptedException {
491 <        ExecutorService e = new DirectExecutorService();
492 <        try {
493 <            e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
494 <            shouldThrow();
495 <        } catch (NullPointerException success) {
496 <        } finally {
592 <            joinPool(e);
491 >        final ExecutorService e = new DirectExecutorService();
492 >        try (PoolCleaner cleaner = cleaner(e)) {
493 >            try {
494 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
495 >                shouldThrow();
496 >            } catch (NullPointerException success) {}
497          }
498      }
499  
# Line 597 | Line 501 | public class AbstractExecutorServiceTest
501       * timed invokeAll(null time unit) throws NPE
502       */
503      public void testTimedInvokeAllNullTimeUnit() throws InterruptedException {
504 <        ExecutorService e = new DirectExecutorService();
505 <        try {
506 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
504 >        final ExecutorService e = new DirectExecutorService();
505 >        try (PoolCleaner cleaner = cleaner(e)) {
506 >            List<Callable<String>> l = new ArrayList<>();
507              l.add(new StringTask());
508 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
509 <            shouldThrow();
510 <        } catch (NullPointerException success) {
511 <        } finally {
608 <            joinPool(e);
508 >            try {
509 >                e.invokeAll(l, randomTimeout(), null);
510 >                shouldThrow();
511 >            } catch (NullPointerException success) {}
512          }
513      }
514  
515      /**
516 <     * timed invokeAll(empty collection) returns empty collection
516 >     * timed invokeAll(empty collection) returns empty list
517       */
518      public void testTimedInvokeAll2() throws InterruptedException {
519 <        ExecutorService e = new DirectExecutorService();
520 <        try {
521 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
519 >        final ExecutorService e = new DirectExecutorService();
520 >        final Collection<Callable<String>> emptyCollection
521 >            = Collections.emptyList();
522 >        try (PoolCleaner cleaner = cleaner(e)) {
523 >            List<Future<String>> r =
524 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
525              assertTrue(r.isEmpty());
620        } finally {
621            joinPool(e);
526          }
527      }
528  
529      /**
530 <     * timed invokeAll(c) throws NPE if c has null elements
530 >     * timed invokeAll(c) throws NullPointerException if c has null elements
531       */
532      public void testTimedInvokeAll3() throws InterruptedException {
533 <        ExecutorService e = new DirectExecutorService();
534 <        try {
535 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
533 >        final ExecutorService e = new DirectExecutorService();
534 >        try (PoolCleaner cleaner = cleaner(e)) {
535 >            List<Callable<String>> l = new ArrayList<>();
536              l.add(new StringTask());
537              l.add(null);
538 <            e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
539 <            shouldThrow();
540 <        } catch (NullPointerException success) {
541 <        } finally {
638 <            joinPool(e);
538 >            try {
539 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
540 >                shouldThrow();
541 >            } catch (NullPointerException success) {}
542          }
543      }
544  
# Line 643 | Line 546 | public class AbstractExecutorServiceTest
546       * get of returned element of invokeAll(c) throws exception on failed task
547       */
548      public void testTimedInvokeAll4() throws Exception {
549 <        ExecutorService e = new DirectExecutorService();
550 <        try {
551 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
549 >        final ExecutorService e = new DirectExecutorService();
550 >        try (PoolCleaner cleaner = cleaner(e)) {
551 >            List<Callable<String>> l = new ArrayList<>();
552              l.add(new NPETask());
553 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
554 <            assertEquals(1, result.size());
555 <            for (Future<String> future : result) {
556 <                try {
557 <                    future.get();
558 <                } catch (ExecutionException success) {
559 <                    assertTrue(success.getCause() instanceof NullPointerException);
560 <                }
553 >            List<Future<String>> futures =
554 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
555 >            assertEquals(1, futures.size());
556 >            try {
557 >                futures.get(0).get();
558 >                shouldThrow();
559 >            } catch (ExecutionException success) {
560 >                assertTrue(success.getCause() instanceof NullPointerException);
561              }
659        } finally {
660            joinPool(e);
562          }
563      }
564  
# Line 665 | Line 566 | public class AbstractExecutorServiceTest
566       * timed invokeAll(c) returns results of all completed tasks in c
567       */
568      public void testTimedInvokeAll5() throws Exception {
569 <        ExecutorService e = new DirectExecutorService();
570 <        try {
571 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
569 >        final ExecutorService e = new DirectExecutorService();
570 >        try (PoolCleaner cleaner = cleaner(e)) {
571 >            List<Callable<String>> l = new ArrayList<>();
572              l.add(new StringTask());
573              l.add(new StringTask());
574 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
575 <            assertEquals(2, result.size());
576 <            for (Future<String> future : result)
574 >            List<Future<String>> futures =
575 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
576 >            assertEquals(2, futures.size());
577 >            for (Future<String> future : futures)
578                  assertSame(TEST_STRING, future.get());
677        } finally {
678            joinPool(e);
579          }
580      }
581  
582      /**
583       * timed invokeAll cancels tasks not completed by timeout
584       */
585 <    public void testTimedInvokeAll6() throws InterruptedException {
586 <        ExecutorService e = new DirectExecutorService();
587 <        try {
588 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
589 <            l.add(new StringTask());
590 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
591 <            l.add(new StringTask());
592 <            List<Future<String>> result = e.invokeAll(l, SMALL_DELAY_MS, TimeUnit.MILLISECONDS);
593 <            assertEquals(3, result.size());
594 <            Iterator<Future<String>> it = result.iterator();
595 <            Future<String> f1 = it.next();
596 <            Future<String> f2 = it.next();
597 <            Future<String> f3 = it.next();
598 <            assertTrue(f1.isDone());
599 <            assertFalse(f1.isCancelled());
600 <            assertTrue(f2.isDone());
601 <            assertTrue(f3.isDone());
602 <            assertTrue(f3.isCancelled());
603 <        } finally {
604 <            joinPool(e);
585 >    public void testTimedInvokeAll6() throws Exception {
586 >        final ExecutorService e = new DirectExecutorService();
587 >        try (PoolCleaner cleaner = cleaner(e)) {
588 >            for (long timeout = timeoutMillis();;) {
589 >                List<Callable<String>> tasks = new ArrayList<>();
590 >                tasks.add(new StringTask("0"));
591 >                tasks.add(Executors.callable(possiblyInterruptedRunnable(timeout),
592 >                                             TEST_STRING));
593 >                tasks.add(new StringTask("2"));
594 >                long startTime = System.nanoTime();
595 >                List<Future<String>> futures =
596 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
597 >                assertEquals(tasks.size(), futures.size());
598 >                assertTrue(millisElapsedSince(startTime) >= timeout);
599 >                for (Future future : futures)
600 >                    assertTrue(future.isDone());
601 >                try {
602 >                    assertEquals("0", futures.get(0).get());
603 >                    assertEquals(TEST_STRING, futures.get(1).get());
604 >                } catch (CancellationException retryWithLongerTimeout) {
605 >                    // unusual delay before starting second task
606 >                    timeout *= 2;
607 >                    if (timeout >= LONG_DELAY_MS / 2)
608 >                        fail("expected exactly one task to be cancelled");
609 >                    continue;
610 >                }
611 >                assertTrue(futures.get(2).isCancelled());
612 >                break;
613 >            }
614          }
615      }
616  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines