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

Comparing jsr166/src/test/tck/ForkJoinPoolTest.java (file contents):
Revision 1.1 by dl, Fri Jul 31 23:02:49 2009 UTC vs.
Revision 1.70 by jsr166, Tue Oct 13 21:18:28 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   */
6  
7 + import static java.util.concurrent.TimeUnit.MILLISECONDS;
8 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
9  
10 < import junit.framework.*;
11 < import java.util.*;
12 < import java.util.concurrent.*;
13 < import java.util.concurrent.locks.*;
14 < import java.security.*;
10 > import java.security.PrivilegedAction;
11 > import java.security.PrivilegedExceptionAction;
12 > import java.util.ArrayList;
13 > import java.util.Collection;
14 > import java.util.List;
15 > import java.util.concurrent.Callable;
16 > import java.util.concurrent.CountDownLatch;
17 > import java.util.concurrent.ExecutionException;
18 > import java.util.concurrent.Executors;
19 > import java.util.concurrent.ExecutorService;
20 > import java.util.concurrent.ForkJoinPool;
21 > import java.util.concurrent.ForkJoinTask;
22 > import java.util.concurrent.ForkJoinWorkerThread;
23 > import java.util.concurrent.Future;
24 > import java.util.concurrent.RecursiveTask;
25 > import java.util.concurrent.RejectedExecutionException;
26 > import java.util.concurrent.atomic.AtomicBoolean;
27 > import java.util.concurrent.locks.ReentrantLock;
28 >
29 > import junit.framework.AssertionFailedError;
30 > import junit.framework.Test;
31 > import junit.framework.TestSuite;
32  
33 < public class ForkJoinPoolTest extends JSR166TestCase{
33 > public class ForkJoinPoolTest extends JSR166TestCase {
34      public static void main(String[] args) {
35 <        junit.textui.TestRunner.run (suite());
35 >        main(suite(), args);
36      }
37 +
38      public static Test suite() {
39          return new TestSuite(ForkJoinPoolTest.class);
40      }
41  
42 <    /**
42 >    /*
43       * Testing coverage notes:
44       *
45       * 1. shutdown and related methods are tested via super.joinPool.
46       *
47       * 2. newTaskFor and adapters are tested in submit/invoke tests
48 <     *
48 >     *
49       * 3. We cannot portably test monitoring methods such as
50       * getStealCount() since they rely ultimately on random task
51       * stealing that may cause tasks not to be stolen/propagated
52       * across threads, especially on uniprocessors.
53 <     *
53 >     *
54       * 4. There are no independently testable ForkJoinWorkerThread
55       * methods, but they are covered here and in task tests.
56       */
# Line 38 | Line 58 | public class ForkJoinPoolTest extends JS
58      // Some classes to test extension and factory methods
59  
60      static class MyHandler implements Thread.UncaughtExceptionHandler {
61 <        int catches = 0;
61 >        volatile int catches = 0;
62          public void uncaughtException(Thread t, Throwable e) {
63              ++catches;
64          }
65      }
66  
67 +    static class MyError extends Error {}
68 +
69      // to test handlers
70      static class FailingFJWSubclass extends ForkJoinWorkerThread {
71          public FailingFJWSubclass(ForkJoinPool p) { super(p) ; }
72 <        protected void onStart() { throw new Error(); }
72 >        protected void onStart() { super.onStart(); throw new MyError(); }
73      }
74  
75 <    static class FailingThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {
76 <        int calls = 0;
77 <        public ForkJoinWorkerThread newThread(ForkJoinPool p){
75 >    static class FailingThreadFactory
76 >            implements ForkJoinPool.ForkJoinWorkerThreadFactory {
77 >        volatile int calls = 0;
78 >        public ForkJoinWorkerThread newThread(ForkJoinPool p) {
79              if (++calls > 1) return null;
80              return new FailingFJWSubclass(p);
81 <        }  
81 >        }
82      }
83  
84 <    static class SubFJP extends ForkJoinPool { // to expose protected
84 >    static class SubFJP extends ForkJoinPool { // to expose protected
85          SubFJP() { super(1); }
86          public int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
87              return super.drainTasksTo(c);
# Line 83 | Line 106 | public class ForkJoinPoolTest extends JS
106      }
107  
108      // A simple recursive task for testing
109 <    static final class FibTask extends RecursiveTask<Integer> {
109 >    static final class FibTask extends RecursiveTask<Integer> {
110          final int number;
111          FibTask(int n) { number = n; }
112 <        public Integer compute() {
112 >        protected Integer compute() {
113              int n = number;
114              if (n <= 1)
115                  return n;
# Line 97 | Line 120 | public class ForkJoinPoolTest extends JS
120      }
121  
122      // A failing task for testing
123 <    static final class FailingTask extends ForkJoinTask<Void> {
123 >    static final class FailingTask extends ForkJoinTask<Void> {
124          public final Void getRawResult() { return null; }
125          protected final void setRawResult(Void mustBeNull) { }
126          protected final boolean exec() { throw new Error(); }
# Line 105 | Line 128 | public class ForkJoinPoolTest extends JS
128      }
129  
130      // Fib needlessly using locking to test ManagedBlockers
131 <    static final class LockingFibTask extends RecursiveTask<Integer> {
131 >    static final class LockingFibTask extends RecursiveTask<Integer> {
132          final int number;
133          final ManagedLocker locker;
134          final ReentrantLock lock;
135 <        LockingFibTask(int n, ManagedLocker locker, ReentrantLock lock) {
136 <            number = n;
135 >        LockingFibTask(int n, ManagedLocker locker, ReentrantLock lock) {
136 >            number = n;
137              this.locker = locker;
138              this.lock = lock;
139          }
140 <        public Integer compute() {
140 >        protected Integer compute() {
141              int n;
142              LockingFibTask f1 = null;
143              LockingFibTask f2 = null;
144              locker.block();
145 <            n = number;
145 >            n = number;
146              if (n > 1) {
147                  f1 = new LockingFibTask(n - 1, locker, lock);
148                  f2 = new LockingFibTask(n - 2, locker, lock);
# Line 134 | Line 157 | public class ForkJoinPoolTest extends JS
157          }
158      }
159  
160 <    /**
161 <     * Succesfully constructed pool reports default factory,
160 >    /**
161 >     * Successfully constructed pool reports default factory,
162       * parallelism and async mode policies, no active threads or
163       * tasks, and quiescent running state.
164       */
165      public void testDefaultInitialState() {
166 <        ForkJoinPool p = null;
167 <        try {
168 <            p = new ForkJoinPool(1);
169 <            assertTrue(p.getFactory() == ForkJoinPool.defaultForkJoinWorkerThreadFactory);
147 <            assertTrue(p.isQuiescent());
148 <            assertTrue(p.getMaintainsParallelism());
166 >        ForkJoinPool p = new ForkJoinPool(1);
167 >        try (PoolCleaner cleaner = cleaner(p)) {
168 >            assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
169 >                       p.getFactory());
170              assertFalse(p.getAsyncMode());
171 <            assertTrue(p.getActiveThreadCount() == 0);
172 <            assertTrue(p.getStealCount() == 0);
173 <            assertTrue(p.getQueuedTaskCount() == 0);
174 <            assertTrue(p.getQueuedSubmissionCount() == 0);
171 >            assertEquals(0, p.getActiveThreadCount());
172 >            assertEquals(0, p.getStealCount());
173 >            assertEquals(0, p.getQueuedTaskCount());
174 >            assertEquals(0, p.getQueuedSubmissionCount());
175              assertFalse(p.hasQueuedSubmissions());
176              assertFalse(p.isShutdown());
177              assertFalse(p.isTerminating());
178              assertFalse(p.isTerminated());
158        } finally {
159            joinPool(p);
179          }
180      }
181  
182 <    /**
183 <     * Constructor throws if size argument is less than zero
182 >    /**
183 >     * Constructor throws if size argument is less than zero
184       */
185      public void testConstructor1() {
186          try {
187              new ForkJoinPool(-1);
188              shouldThrow();
189 <        }
171 <        catch (IllegalArgumentException success){}
189 >        } catch (IllegalArgumentException success) {}
190      }
191  
192 <    /**
193 <     * Constructor throws if factory argument is null
192 >    /**
193 >     * Constructor throws if factory argument is null
194       */
195      public void testConstructor2() {
196          try {
197 <            new ForkJoinPool(1, null);
197 >            new ForkJoinPool(1, null, null, false);
198              shouldThrow();
199 <        }
182 <        catch (NullPointerException success){}  
199 >        } catch (NullPointerException success) {}
200      }
201  
202 <
203 <    /**
187 <     * getParallelism returns size set in constructor
202 >    /**
203 >     * getParallelism returns size set in constructor
204       */
205      public void testGetParallelism() {
206 <        ForkJoinPool p = null;
207 <        try {
208 <            p = new ForkJoinPool(1);
193 <            assertTrue(p.getParallelism() == 1);
194 <        } finally {
195 <            joinPool(p);
196 <        }
197 <    }
198 <
199 <    /**
200 <     * setParallelism changes reported parallelism level.
201 <     */
202 <    public void testSetParallelism() {
203 <        ForkJoinPool p = null;
204 <        try {
205 <            p = new ForkJoinPool(1);
206 <            assertTrue(p.getParallelism() == 1);
207 <            p.setParallelism(2);
208 <            assertTrue(p.getParallelism() == 2);
209 <        } finally {
210 <            joinPool(p);
211 <        }
212 <    }
213 <
214 <    /**
215 <     * setParallelism with argument <= 0 throws exception
216 <     */
217 <    public void testSetParallelism2() {
218 <        ForkJoinPool p = null;
219 <        try {
220 <            p = new ForkJoinPool(1);
221 <            assertTrue(p.getParallelism() == 1);
222 <            p.setParallelism(-2);
223 <            shouldThrow();
224 <        }catch (IllegalArgumentException success){
225 <        } finally {
226 <            joinPool(p);
206 >        ForkJoinPool p = new ForkJoinPool(1);
207 >        try (PoolCleaner cleaner = cleaner(p)) {
208 >            assertEquals(1, p.getParallelism());
209          }
210      }
211  
212 <    /**
212 >    /**
213       * getPoolSize returns number of started workers.
214       */
215      public void testGetPoolSize() {
216 <        ForkJoinPool p = null;
217 <        try {
218 <            p = new ForkJoinPool(1);
219 <            assertTrue(p.getPoolSize() == 0);
220 <            Future<String> future = p.submit(new StringTask());
221 <            assertTrue(p.getPoolSize() == 1);
222 <
223 <        } finally {
224 <            joinPool(p);
225 <        }
226 <    }
227 <
228 <    /**
229 <     * setMaximumPoolSize changes size reported by getMaximumPoolSize.
230 <     */
231 <    public void testSetMaximumPoolSize() {
232 <        ForkJoinPool p = null;
251 <        try {
252 <            p = new ForkJoinPool(1);
253 <            p.setMaximumPoolSize(2);
254 <            assertTrue(p.getMaximumPoolSize() == 2);
255 <        } finally {
256 <            joinPool(p);
257 <        }
258 <    }
259 <
260 <    /**
261 <     * setMaximumPoolSize with argument <= 0 throws exception
262 <     */
263 <    public void testSetMaximumPoolSize2() {
264 <        ForkJoinPool p = null;
265 <        try {
266 <            p = new ForkJoinPool(1);
267 <            p.setMaximumPoolSize(-2);
268 <            shouldThrow();
269 <        }catch (IllegalArgumentException success){
270 <        } finally {
271 <            joinPool(p);
216 >        final CountDownLatch taskStarted = new CountDownLatch(1);
217 >        final CountDownLatch done = new CountDownLatch(1);
218 >        final ForkJoinPool p = new ForkJoinPool(1);
219 >        try (PoolCleaner cleaner = cleaner(p)) {
220 >            assertEquals(0, p.getActiveThreadCount());
221 >            final Runnable task = new CheckedRunnable() {
222 >                public void realRun() throws InterruptedException {
223 >                    taskStarted.countDown();
224 >                    assertEquals(1, p.getPoolSize());
225 >                    assertEquals(1, p.getActiveThreadCount());
226 >                    done.await();
227 >                }};
228 >            Future<?> future = p.submit(task);
229 >            await(taskStarted);
230 >            assertEquals(1, p.getPoolSize());
231 >            assertEquals(1, p.getActiveThreadCount());
232 >            done.countDown();
233          }
234 +        assertEquals(0, p.getPoolSize());
235 +        assertEquals(0, p.getActiveThreadCount());
236      }
237  
238 <    /**
239 <     * setMaintainsParallelism changes policy reported by
277 <     * getMaintainsParallelism.
278 <     */
279 <    public void testSetMaintainsParallelism() {
280 <        ForkJoinPool p = null;
281 <        try {
282 <            p = new ForkJoinPool(1);
283 <            p.setMaintainsParallelism(false);
284 <            assertFalse(p.getMaintainsParallelism());
285 <        } finally {
286 <            joinPool(p);
287 <        }
288 <    }
289 <    
290 <    /**
291 <     * setAsyncMode changes policy reported by
292 <     * getAsyncMode.
238 >    /**
239 >     * awaitTermination on a non-shutdown pool times out
240       */
241 <    public void testSetAsyncMode() {
242 <        ForkJoinPool p = null;
243 <        try {
244 <            p = new ForkJoinPool(1);
245 <            p.setAsyncMode(true);
246 <            assertTrue(p.getAsyncMode());
247 <        } finally {
248 <            joinPool(p);
241 >    public void testAwaitTermination_timesOut() throws InterruptedException {
242 >        ForkJoinPool p = new ForkJoinPool(1);
243 >        try (PoolCleaner cleaner = cleaner(p)) {
244 >            assertFalse(p.isTerminated());
245 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
246 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
247 >            assertFalse(p.awaitTermination(-1L, NANOSECONDS));
248 >            assertFalse(p.awaitTermination(-1L, MILLISECONDS));
249 >            assertFalse(p.awaitTermination(0L, NANOSECONDS));
250 >            assertFalse(p.awaitTermination(0L, MILLISECONDS));
251 >            long timeoutNanos = 999999L;
252 >            long startTime = System.nanoTime();
253 >            assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
254 >            assertTrue(System.nanoTime() - startTime >= timeoutNanos);
255 >            assertFalse(p.isTerminated());
256 >            startTime = System.nanoTime();
257 >            long timeoutMillis = timeoutMillis();
258 >            assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
259 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
260 >            assertFalse(p.isTerminated());
261 >            p.shutdown();
262 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
263 >            assertTrue(p.isTerminated());
264          }
265      }
266  
267 <    /**
267 >    /**
268       * setUncaughtExceptionHandler changes handler for uncaught exceptions.
269       *
270       * Additionally tests: Overriding ForkJoinWorkerThread.onStart
271       * performs its defined action
272       */
273 <    public void testSetUncaughtExceptionHandler() {
274 <        ForkJoinPool p = null;
275 <        try {
276 <            p = new ForkJoinPool(1, new FailingThreadFactory());
277 <            MyHandler eh = new MyHandler();
278 <            p.setUncaughtExceptionHandler(eh);
279 <            assertEquals(eh, p.getUncaughtExceptionHandler());
280 <            p.execute(new FailingTask());
281 <            Thread.sleep(MEDIUM_DELAY_MS);
282 <            assertTrue(eh.catches > 0);
283 <        } catch(InterruptedException e){
284 <            unexpectedException();
285 <        } finally {
286 <            joinPool(p);
287 <        }
288 <    }
289 <
290 <    /**
291 <     * setUncaughtExceptionHandler of null removes handler
330 <     */
331 <    public void testSetUncaughtExceptionHandler2() {
332 <        ForkJoinPool p = null;
333 <        try {
334 <            p = new ForkJoinPool(1);
335 <            p.setUncaughtExceptionHandler(null);
336 <            assertNull(p.getUncaughtExceptionHandler());
337 <        } finally {
338 <            joinPool(p);
273 >    public void testSetUncaughtExceptionHandler() throws InterruptedException {
274 >        final CountDownLatch uehInvoked = new CountDownLatch(1);
275 >        final Thread.UncaughtExceptionHandler ueh =
276 >            new Thread.UncaughtExceptionHandler() {
277 >                public void uncaughtException(Thread t, Throwable e) {
278 >                    threadAssertTrue(e instanceof MyError);
279 >                    threadAssertTrue(t instanceof FailingFJWSubclass);
280 >                    uehInvoked.countDown();
281 >                }};
282 >        ForkJoinPool p = new ForkJoinPool(1, new FailingThreadFactory(),
283 >                                          ueh, false);
284 >        try (PoolCleaner cleaner = cleaner(p)) {
285 >            assertSame(ueh, p.getUncaughtExceptionHandler());
286 >            try {
287 >                p.execute(new FibTask(8));
288 >                await(uehInvoked);
289 >            } finally {
290 >                p.shutdownNow(); // failure might have prevented processing task
291 >            }
292          }
293      }
294  
295 +    /**
296 +     * After invoking a single task, isQuiescent eventually becomes
297 +     * true, at which time queues are empty, threads are not active,
298 +     * the task has completed successfully, and construction
299 +     * parameters continue to hold
300 +     */
301 +    public void testIsQuiescent() throws Exception {
302 +        ForkJoinPool p = new ForkJoinPool(2);
303 +        try (PoolCleaner cleaner = cleaner(p)) {
304 +            assertTrue(p.isQuiescent());
305 +            long startTime = System.nanoTime();
306 +            FibTask f = new FibTask(20);
307 +            p.invoke(f);
308 +            assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
309 +                       p.getFactory());
310 +            while (! p.isQuiescent()) {
311 +                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
312 +                    throw new AssertionFailedError("timed out");
313 +                assertFalse(p.getAsyncMode());
314 +                assertFalse(p.isShutdown());
315 +                assertFalse(p.isTerminating());
316 +                assertFalse(p.isTerminated());
317 +                Thread.yield();
318 +            }
319  
343    /**
344     * After invoking a single task, isQuiescent is true,
345     * queues are empty, threads are not active, and
346     * construction parameters continue to hold
347     */
348    public void testisQuiescent() {
349        ForkJoinPool p = null;
350        try {
351            p = new ForkJoinPool(2);
352            p.invoke(new FibTask(20));
353            assertTrue(p.getFactory() == ForkJoinPool.defaultForkJoinWorkerThreadFactory);
354            Thread.sleep(MEDIUM_DELAY_MS);
320              assertTrue(p.isQuiescent());
356            assertTrue(p.getMaintainsParallelism());
321              assertFalse(p.getAsyncMode());
322 <            assertTrue(p.getActiveThreadCount() == 0);
323 <            assertTrue(p.getQueuedTaskCount() == 0);
360 <            assertTrue(p.getQueuedSubmissionCount() == 0);
322 >            assertEquals(0, p.getQueuedTaskCount());
323 >            assertEquals(0, p.getQueuedSubmissionCount());
324              assertFalse(p.hasQueuedSubmissions());
325 +            while (p.getActiveThreadCount() != 0
326 +                   && millisElapsedSince(startTime) < LONG_DELAY_MS)
327 +                Thread.yield();
328              assertFalse(p.isShutdown());
329              assertFalse(p.isTerminating());
330              assertFalse(p.isTerminated());
331 <        } catch(InterruptedException e){
332 <            unexpectedException();
333 <        } finally {
368 <            joinPool(p);
331 >            assertTrue(f.isDone());
332 >            assertEquals(6765, (int) f.get());
333 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
334          }
335      }
336  
337      /**
338       * Completed submit(ForkJoinTask) returns result
339       */
340 <    public void testSubmitForkJoinTask() {
341 <        ForkJoinPool p = null;
342 <        try {
378 <            p = new ForkJoinPool(1);
340 >    public void testSubmitForkJoinTask() throws Throwable {
341 >        ForkJoinPool p = new ForkJoinPool(1);
342 >        try (PoolCleaner cleaner = cleaner(p)) {
343              ForkJoinTask<Integer> f = p.submit(new FibTask(8));
344 <            int r = f.get();
381 <            assertTrue(r == 21);
382 <        } catch (ExecutionException ex) {
383 <            unexpectedException();
384 <        } catch (InterruptedException ex) {
385 <            unexpectedException();
386 <        } finally {
387 <            joinPool(p);
344 >            assertEquals(21, (int) f.get());
345          }
346      }
347  
# Line 392 | Line 349 | public class ForkJoinPoolTest extends JS
349       * A task submitted after shutdown is rejected
350       */
351      public void testSubmitAfterShutdown() {
352 <        ForkJoinPool p = null;
353 <        try {
397 <            p = new ForkJoinPool(1);
352 >        ForkJoinPool p = new ForkJoinPool(1);
353 >        try (PoolCleaner cleaner = cleaner(p)) {
354              p.shutdown();
355              assertTrue(p.isShutdown());
356 <            ForkJoinTask<Integer> f = p.submit(new FibTask(8));
357 <            shouldThrow();
358 <        } catch (RejectedExecutionException success) {
359 <        } finally {
404 <            joinPool(p);
356 >            try {
357 >                ForkJoinTask<Integer> f = p.submit(new FibTask(8));
358 >                shouldThrow();
359 >            } catch (RejectedExecutionException success) {}
360          }
361      }
362  
363      /**
364       * Pool maintains parallelism when using ManagedBlocker
365       */
366 <    public void testBlockingForkJoinTask() {
367 <        ForkJoinPool p = null;
366 >    public void testBlockingForkJoinTask() throws Throwable {
367 >        ForkJoinPool p = new ForkJoinPool(4);
368          try {
414            p = new ForkJoinPool(4);
369              ReentrantLock lock = new ReentrantLock();
370              ManagedLocker locker = new ManagedLocker(lock);
371 <            ForkJoinTask<Integer> f = new LockingFibTask(30, locker, lock);
371 >            ForkJoinTask<Integer> f = new LockingFibTask(20, locker, lock);
372              p.execute(f);
373 <            assertTrue(p.getPoolSize() >= 4);
420 <            int r = f.get();
421 <            assertTrue(r ==  832040);
422 <        } catch (ExecutionException ex) {
423 <            unexpectedException();
424 <        } catch (InterruptedException ex) {
425 <            unexpectedException();
373 >            assertEquals(6765, (int) f.get());
374          } finally {
375 <            joinPool(p);
375 >            p.shutdownNow(); // don't wait out shutdown
376          }
377      }
378  
# Line 432 | Line 380 | public class ForkJoinPoolTest extends JS
380       * pollSubmission returns unexecuted submitted task, if present
381       */
382      public void testPollSubmission() {
383 <        SubFJP p = null;
384 <        try {
385 <            p = new SubFJP();
386 <            ForkJoinTask a = p.submit(new MediumRunnable());
387 <            ForkJoinTask b = p.submit(new MediumRunnable());
388 <            ForkJoinTask c = p.submit(new MediumRunnable());
383 >        final CountDownLatch done = new CountDownLatch(1);
384 >        SubFJP p = new SubFJP();
385 >        try (PoolCleaner cleaner = cleaner(p)) {
386 >            ForkJoinTask a = p.submit(awaiter(done));
387 >            ForkJoinTask b = p.submit(awaiter(done));
388 >            ForkJoinTask c = p.submit(awaiter(done));
389              ForkJoinTask r = p.pollSubmission();
390              assertTrue(r == a || r == b || r == c);
391              assertFalse(r.isDone());
392 <        } finally {
445 <            joinPool(p);
392 >            done.countDown();
393          }
394      }
395  
# Line 450 | Line 397 | public class ForkJoinPoolTest extends JS
397       * drainTasksTo transfers unexecuted submitted tasks, if present
398       */
399      public void testDrainTasksTo() {
400 <        SubFJP p = null;
401 <        try {
402 <            p = new SubFJP();
403 <            ForkJoinTask a = p.submit(new MediumRunnable());
404 <            ForkJoinTask b = p.submit(new MediumRunnable());
405 <            ForkJoinTask c = p.submit(new MediumRunnable());
400 >        final CountDownLatch done = new CountDownLatch(1);
401 >        SubFJP p = new SubFJP();
402 >        try (PoolCleaner cleaner = cleaner(p)) {
403 >            ForkJoinTask a = p.submit(awaiter(done));
404 >            ForkJoinTask b = p.submit(awaiter(done));
405 >            ForkJoinTask c = p.submit(awaiter(done));
406              ArrayList<ForkJoinTask> al = new ArrayList();
407              p.drainTasksTo(al);
408              assertTrue(al.size() > 0);
# Line 463 | Line 410 | public class ForkJoinPoolTest extends JS
410                  assertTrue(r == a || r == b || r == c);
411                  assertFalse(r.isDone());
412              }
413 <        } finally {
467 <            joinPool(p);
413 >            done.countDown();
414          }
415      }
416  
471    
417      // FJ Versions of AbstractExecutorService tests
418  
419      /**
420       * execute(runnable) runs it to completion
421       */
422 <    public void testExecuteRunnable() {
423 <        try {
424 <            ExecutorService e = new ForkJoinPool(1);
425 <            TrackedShortRunnable task = new TrackedShortRunnable();
426 <            assertFalse(task.done);
427 <            Future<?> future = e.submit(task);
428 <            future.get();
429 <            assertTrue(task.done);
430 <        }
431 <        catch (ExecutionException ex) {
432 <            unexpectedException();
433 <        }
434 <        catch (InterruptedException ex) {
490 <            unexpectedException();
422 >    public void testExecuteRunnable() throws Throwable {
423 >        ExecutorService e = new ForkJoinPool(1);
424 >        try (PoolCleaner cleaner = cleaner(e)) {
425 >            final AtomicBoolean done = new AtomicBoolean(false);
426 >            Future<?> future = e.submit(new CheckedRunnable() {
427 >                public void realRun() {
428 >                    done.set(true);
429 >                }});
430 >            assertNull(future.get());
431 >            assertNull(future.get(0, MILLISECONDS));
432 >            assertTrue(done.get());
433 >            assertTrue(future.isDone());
434 >            assertFalse(future.isCancelled());
435          }
436      }
437  
494
438      /**
439       * Completed submit(callable) returns result
440       */
441 <    public void testSubmitCallable() {
442 <        try {
443 <            ExecutorService e = new ForkJoinPool(1);
441 >    public void testSubmitCallable() throws Throwable {
442 >        ExecutorService e = new ForkJoinPool(1);
443 >        try (PoolCleaner cleaner = cleaner(e)) {
444              Future<String> future = e.submit(new StringTask());
445 <            String result = future.get();
446 <            assertSame(TEST_STRING, result);
447 <        }
505 <        catch (ExecutionException ex) {
506 <            unexpectedException();
507 <        }
508 <        catch (InterruptedException ex) {
509 <            unexpectedException();
445 >            assertSame(TEST_STRING, future.get());
446 >            assertTrue(future.isDone());
447 >            assertFalse(future.isCancelled());
448          }
449      }
450  
451      /**
452       * Completed submit(runnable) returns successfully
453       */
454 <    public void testSubmitRunnable() {
455 <        try {
456 <            ExecutorService e = new ForkJoinPool(1);
454 >    public void testSubmitRunnable() throws Throwable {
455 >        ExecutorService e = new ForkJoinPool(1);
456 >        try (PoolCleaner cleaner = cleaner(e)) {
457              Future<?> future = e.submit(new NoOpRunnable());
458 <            future.get();
458 >            assertNull(future.get());
459              assertTrue(future.isDone());
460 <        }
523 <        catch (ExecutionException ex) {
524 <            unexpectedException();
525 <        }
526 <        catch (InterruptedException ex) {
527 <            unexpectedException();
460 >            assertFalse(future.isCancelled());
461          }
462      }
463  
464      /**
465       * Completed submit(runnable, result) returns result
466       */
467 <    public void testSubmitRunnable2() {
468 <        try {
469 <            ExecutorService e = new ForkJoinPool(1);
467 >    public void testSubmitRunnable2() throws Throwable {
468 >        ExecutorService e = new ForkJoinPool(1);
469 >        try (PoolCleaner cleaner = cleaner(e)) {
470              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
471 <            String result = future.get();
472 <            assertSame(TEST_STRING, result);
473 <        }
541 <        catch (ExecutionException ex) {
542 <            unexpectedException();
543 <        }
544 <        catch (InterruptedException ex) {
545 <            unexpectedException();
471 >            assertSame(TEST_STRING, future.get());
472 >            assertTrue(future.isDone());
473 >            assertFalse(future.isCancelled());
474          }
475      }
476  
549
477      /**
478 <     * A submitted privileged action to completion
478 >     * A submitted privileged action runs to completion
479       */
480 <    public void testSubmitPrivilegedAction() {
481 <        Policy savedPolicy = null;
482 <        try {
483 <            savedPolicy = Policy.getPolicy();
484 <            AdjustablePolicy policy = new AdjustablePolicy();
558 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
559 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
560 <            Policy.setPolicy(policy);
561 <        } catch(AccessControlException ok) {
562 <            return;
563 <        }
564 <        try {
480 >    public void testSubmitPrivilegedAction() throws Exception {
481 >        final Callable callable = Executors.callable(new PrivilegedAction() {
482 >                public Object run() { return TEST_STRING; }});
483 >        Runnable r = new CheckedRunnable() {
484 >        public void realRun() throws Exception {
485              ExecutorService e = new ForkJoinPool(1);
486 <            Future future = e.submit(Executors.callable(new PrivilegedAction() {
487 <                    public Object run() {
488 <                        return TEST_STRING;
569 <                    }}));
570 <
571 <            Object result = future.get();
572 <            assertSame(TEST_STRING, result);
573 <        }
574 <        catch (ExecutionException ex) {
575 <            unexpectedException();
576 <        }
577 <        catch (InterruptedException ex) {
578 <            unexpectedException();
579 <        }
580 <        finally {
581 <            try {
582 <                Policy.setPolicy(savedPolicy);
583 <            } catch(AccessControlException ok) {
584 <                return;
486 >            try (PoolCleaner cleaner = cleaner(e)) {
487 >                Future future = e.submit(callable);
488 >                assertSame(TEST_STRING, future.get());
489              }
490 <        }
490 >        }};
491 >
492 >        runWithPermissions(r, new RuntimePermission("modifyThread"));
493      }
494  
495      /**
496 <     * A submitted a privileged exception action runs to completion
496 >     * A submitted privileged exception action runs to completion
497       */
498 <    public void testSubmitPrivilegedExceptionAction() {
499 <        Policy savedPolicy = null;
500 <        try {
501 <            savedPolicy = Policy.getPolicy();
502 <            AdjustablePolicy policy = new AdjustablePolicy();
503 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
598 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
599 <            Policy.setPolicy(policy);
600 <        } catch(AccessControlException ok) {
601 <            return;
602 <        }
603 <
604 <        try {
498 >    public void testSubmitPrivilegedExceptionAction() throws Exception {
499 >        final Callable callable =
500 >            Executors.callable(new PrivilegedExceptionAction() {
501 >                public Object run() { return TEST_STRING; }});
502 >        Runnable r = new CheckedRunnable() {
503 >        public void realRun() throws Exception {
504              ExecutorService e = new ForkJoinPool(1);
505 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
506 <                    public Object run() {
507 <                        return TEST_STRING;
508 <                    }}));
505 >            try (PoolCleaner cleaner = cleaner(e)) {
506 >                Future future = e.submit(callable);
507 >                assertSame(TEST_STRING, future.get());
508 >            }
509 >        }};
510  
511 <            Object result = future.get();
612 <            assertSame(TEST_STRING, result);
613 <        }
614 <        catch (ExecutionException ex) {
615 <            unexpectedException();
616 <        }
617 <        catch (InterruptedException ex) {
618 <            unexpectedException();
619 <        }
620 <        finally {
621 <            Policy.setPolicy(savedPolicy);
622 <        }
511 >        runWithPermissions(r, new RuntimePermission("modifyThread"));
512      }
513  
514      /**
515       * A submitted failed privileged exception action reports exception
516       */
517 <    public void testSubmitFailedPrivilegedExceptionAction() {
518 <        Policy savedPolicy = null;
519 <        try {
520 <            savedPolicy = Policy.getPolicy();
521 <            AdjustablePolicy policy = new AdjustablePolicy();
522 <            policy.addPermission(new RuntimePermission("getContextClassLoader"));
634 <            policy.addPermission(new RuntimePermission("setContextClassLoader"));
635 <            Policy.setPolicy(policy);
636 <        } catch(AccessControlException ok) {
637 <            return;
638 <        }
639 <
640 <
641 <        try {
517 >    public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
518 >        final Callable callable =
519 >            Executors.callable(new PrivilegedExceptionAction() {
520 >                public Object run() { throw new IndexOutOfBoundsException(); }});
521 >        Runnable r = new CheckedRunnable() {
522 >        public void realRun() throws Exception {
523              ExecutorService e = new ForkJoinPool(1);
524 <            Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
525 <                    public Object run() throws Exception {
526 <                        throw new IndexOutOfBoundsException();
527 <                    }}));
524 >            try (PoolCleaner cleaner = cleaner(e)) {
525 >                Future future = e.submit(callable);
526 >                try {
527 >                    future.get();
528 >                    shouldThrow();
529 >                } catch (ExecutionException success) {
530 >                    assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
531 >                }
532 >            }
533 >        }};
534  
535 <            Object result = future.get();
649 <            shouldThrow();
650 <        }
651 <        catch (ExecutionException success) {
652 <        } catch (CancellationException success) {
653 <        } catch (InterruptedException ex) {
654 <            unexpectedException();
655 <        }
656 <        finally {
657 <            Policy.setPolicy(savedPolicy);
658 <        }
535 >        runWithPermissions(r, new RuntimePermission("modifyThread"));
536      }
537  
538      /**
539 <     * execute(null runnable) throws NPE
539 >     * execute(null runnable) throws NullPointerException
540       */
541      public void testExecuteNullRunnable() {
542 <        try {
543 <            ExecutorService e = new ForkJoinPool(1);
544 <            TrackedShortRunnable task = null;
545 <            Future<?> future = e.submit(task);
546 <            shouldThrow();
547 <        }
671 <        catch (NullPointerException success) {
672 <        }
673 <        catch (Exception ex) {
674 <            unexpectedException();
542 >        ExecutorService e = new ForkJoinPool(1);
543 >        try (PoolCleaner cleaner = cleaner(e)) {
544 >            try {
545 >                Future<?> future = e.submit((Runnable) null);
546 >                shouldThrow();
547 >            } catch (NullPointerException success) {}
548          }
549      }
550  
678
551      /**
552 <     * submit(null callable) throws NPE
552 >     * submit(null callable) throws NullPointerException
553       */
554      public void testSubmitNullCallable() {
555 <        try {
556 <            ExecutorService e = new ForkJoinPool(1);
557 <            StringTask t = null;
558 <            Future<String> future = e.submit(t);
559 <            shouldThrow();
560 <        }
689 <        catch (NullPointerException success) {
690 <        }
691 <        catch (Exception ex) {
692 <            unexpectedException();
555 >        ExecutorService e = new ForkJoinPool(1);
556 >        try (PoolCleaner cleaner = cleaner(e)) {
557 >            try {
558 >                Future<String> future = e.submit((Callable) null);
559 >                shouldThrow();
560 >            } catch (NullPointerException success) {}
561          }
562      }
563  
696
564      /**
565 <     *  Blocking on submit(callable) throws InterruptedException if
566 <     *  caller interrupted.
567 <     */
568 <    public void testInterruptedSubmit() {
569 <        final ForkJoinPool p = new ForkJoinPool(1);
570 <        Thread t = new Thread(new Runnable() {
571 <                public void run() {
572 <                    try {
573 <                        p.submit(new Callable<Object>() {
574 <                                public Object call() {
575 <                                    try {
576 <                                        Thread.sleep(MEDIUM_DELAY_MS);
577 <                                        shouldThrow();
578 <                                    } catch(InterruptedException e){
579 <                                    }
580 <                                    return null;
581 <                                }
582 <                            }).get();
716 <                    } catch(InterruptedException success){
717 <                    } catch(Exception e) {
718 <                        unexpectedException();
719 <                    }
720 <
721 <                }
722 <            });
723 <        try {
565 >     * submit(callable).get() throws InterruptedException if interrupted
566 >     */
567 >    public void testInterruptedSubmit() throws InterruptedException {
568 >        final CountDownLatch submitted    = new CountDownLatch(1);
569 >        final CountDownLatch quittingTime = new CountDownLatch(1);
570 >        final Callable<Void> awaiter = new CheckedCallable<Void>() {
571 >            public Void realCall() throws InterruptedException {
572 >                assertTrue(quittingTime.await(2*LONG_DELAY_MS, MILLISECONDS));
573 >                return null;
574 >            }};
575 >        final ExecutorService p = new ForkJoinPool(1);
576 >        try (PoolCleaner cleaner = cleaner(p, quittingTime)) {
577 >            Thread t = new Thread(new CheckedInterruptedRunnable() {
578 >                public void realRun() throws Exception {
579 >                    Future<Void> future = p.submit(awaiter);
580 >                    submitted.countDown();
581 >                    future.get();
582 >                }});
583              t.start();
584 <            Thread.sleep(SHORT_DELAY_MS);
584 >            await(submitted);
585              t.interrupt();
586 <        } catch(Exception e){
728 <            unexpectedException();
586 >            awaitTermination(t);
587          }
730        joinPool(p);
588      }
589  
590      /**
591 <     *  get of submit(callable) throws ExecutionException if callable
592 <     *  throws exception
591 >     * get of submit(callable) throws ExecutionException if callable
592 >     * throws exception
593       */
594 <    public void testSubmitEE() {
594 >    public void testSubmitEE() throws Throwable {
595          ForkJoinPool p = new ForkJoinPool(1);
596 <
597 <        try {
598 <            Callable c = new Callable() {
599 <                    public Object call() {
600 <                        int i = 5/0;
601 <                        return Boolean.TRUE;
602 <                    }
603 <                };
747 <
748 <            for(int i =0; i < 5; i++){
749 <                p.submit(c).get();
596 >        try (PoolCleaner cleaner = cleaner(p)) {
597 >            try {
598 >                p.submit(new Callable() {
599 >                        public Object call() { throw new ArithmeticException(); }})
600 >                    .get();
601 >                shouldThrow();
602 >            } catch (ExecutionException success) {
603 >                assertTrue(success.getCause() instanceof ArithmeticException);
604              }
751
752            shouldThrow();
605          }
606 <        catch(ExecutionException success){
607 <        } catch (CancellationException success) {
608 <        } catch(Exception e) {
609 <            unexpectedException();
606 >    }
607 >
608 >    /**
609 >     * invokeAny(null) throws NullPointerException
610 >     */
611 >    public void testInvokeAny1() throws Throwable {
612 >        ExecutorService e = new ForkJoinPool(1);
613 >        try (PoolCleaner cleaner = cleaner(e)) {
614 >            try {
615 >                e.invokeAny(null);
616 >                shouldThrow();
617 >            } catch (NullPointerException success) {}
618          }
759        joinPool(p);
619      }
620  
621      /**
622 <     * invokeAny(null) throws NPE
622 >     * invokeAny(empty collection) throws IllegalArgumentException
623       */
624 <    public void testInvokeAny1() {
624 >    public void testInvokeAny2() throws Throwable {
625          ExecutorService e = new ForkJoinPool(1);
626 <        try {
627 <            e.invokeAny(null);
628 <        } catch (NullPointerException success) {
629 <        } catch(Exception ex) {
630 <            unexpectedException();
772 <        } finally {
773 <            joinPool(e);
626 >        try (PoolCleaner cleaner = cleaner(e)) {
627 >            try {
628 >                e.invokeAny(new ArrayList<Callable<String>>());
629 >                shouldThrow();
630 >            } catch (IllegalArgumentException success) {}
631          }
632      }
633  
634      /**
635 <     * invokeAny(empty collection) throws IAE
635 >     * invokeAny(c) throws NullPointerException if c has a single null element
636       */
637 <    public void testInvokeAny2() {
637 >    public void testInvokeAny3() throws Throwable {
638          ExecutorService e = new ForkJoinPool(1);
639 <        try {
640 <            e.invokeAny(new ArrayList<Callable<String>>());
641 <        } catch (IllegalArgumentException success) {
642 <        } catch(Exception ex) {
643 <            unexpectedException();
644 <        } finally {
645 <            joinPool(e);
639 >        try (PoolCleaner cleaner = cleaner(e)) {
640 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
641 >            l.add(null);
642 >            try {
643 >                e.invokeAny(l);
644 >                shouldThrow();
645 >            } catch (NullPointerException success) {}
646          }
647      }
648  
649      /**
650 <     * invokeAny(c) throws NPE if c has null elements
650 >     * invokeAny(c) throws NullPointerException if c has null elements
651       */
652 <    public void testInvokeAny3() {
652 >    public void testInvokeAny4() throws Throwable {
653 >        CountDownLatch latch = new CountDownLatch(1);
654          ExecutorService e = new ForkJoinPool(1);
655 <        try {
656 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
657 <            l.add(new StringTask());
655 >        try (PoolCleaner cleaner = cleaner(e)) {
656 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
657 >            l.add(latchAwaitingStringTask(latch));
658              l.add(null);
659 <            e.invokeAny(l);
660 <        } catch (NullPointerException success) {
661 <        } catch(Exception ex) {
662 <            ex.printStackTrace();
663 <            unexpectedException();
806 <        } finally {
807 <            joinPool(e);
659 >            try {
660 >                e.invokeAny(l);
661 >                shouldThrow();
662 >            } catch (NullPointerException success) {}
663 >            latch.countDown();
664          }
665      }
666  
667      /**
668       * invokeAny(c) throws ExecutionException if no task in c completes
669       */
670 <    public void testInvokeAny4() {
670 >    public void testInvokeAny5() throws Throwable {
671          ExecutorService e = new ForkJoinPool(1);
672 <        try {
673 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
672 >        try (PoolCleaner cleaner = cleaner(e)) {
673 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
674              l.add(new NPETask());
675 <            e.invokeAny(l);
676 <        } catch(ExecutionException success) {
677 <        } catch (CancellationException success) {
678 <        } catch(Exception ex) {
679 <            unexpectedException();
680 <        } finally {
825 <            joinPool(e);
675 >            try {
676 >                e.invokeAny(l);
677 >                shouldThrow();
678 >            } catch (ExecutionException success) {
679 >                assertTrue(success.getCause() instanceof NullPointerException);
680 >            }
681          }
682      }
683  
684      /**
685       * invokeAny(c) returns result of some task in c if at least one completes
686       */
687 <    public void testInvokeAny5() {
687 >    public void testInvokeAny6() throws Throwable {
688          ExecutorService e = new ForkJoinPool(1);
689 <        try {
690 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
689 >        try (PoolCleaner cleaner = cleaner(e)) {
690 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
691              l.add(new StringTask());
692              l.add(new StringTask());
693              String result = e.invokeAny(l);
694              assertSame(TEST_STRING, result);
840        } catch (ExecutionException success) {
841        } catch (CancellationException success) {
842        } catch(Exception ex) {
843            unexpectedException();
844        } finally {
845            joinPool(e);
695          }
696      }
697  
698      /**
699 <     * invokeAll(null) throws NPE
699 >     * invokeAll(null) throws NullPointerException
700       */
701 <    public void testInvokeAll1() {
701 >    public void testInvokeAll1() throws Throwable {
702          ExecutorService e = new ForkJoinPool(1);
703 <        try {
704 <            e.invokeAll(null);
705 <        } catch (NullPointerException success) {
706 <        } catch(Exception ex) {
707 <            unexpectedException();
859 <        } finally {
860 <            joinPool(e);
703 >        try (PoolCleaner cleaner = cleaner(e)) {
704 >            try {
705 >                e.invokeAll(null);
706 >                shouldThrow();
707 >            } catch (NullPointerException success) {}
708          }
709      }
710  
711      /**
712       * invokeAll(empty collection) returns empty collection
713       */
714 <    public void testInvokeAll2() {
714 >    public void testInvokeAll2() throws InterruptedException {
715          ExecutorService e = new ForkJoinPool(1);
716 <        try {
717 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
716 >        try (PoolCleaner cleaner = cleaner(e)) {
717 >            List<Future<String>> r
718 >                = e.invokeAll(new ArrayList<Callable<String>>());
719              assertTrue(r.isEmpty());
872        } catch(Exception ex) {
873            unexpectedException();
874        } finally {
875            joinPool(e);
720          }
721      }
722  
723      /**
724 <     * invokeAll(c) throws NPE if c has null elements
724 >     * invokeAll(c) throws NullPointerException if c has null elements
725       */
726 <    public void testInvokeAll3() {
726 >    public void testInvokeAll3() throws InterruptedException {
727          ExecutorService e = new ForkJoinPool(1);
728 <        try {
729 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
728 >        try (PoolCleaner cleaner = cleaner(e)) {
729 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
730              l.add(new StringTask());
731              l.add(null);
732 <            e.invokeAll(l);
733 <        } catch (NullPointerException success) {
734 <        } catch(Exception ex) {
735 <            unexpectedException();
892 <        } finally {
893 <            joinPool(e);
732 >            try {
733 >                e.invokeAll(l);
734 >                shouldThrow();
735 >            } catch (NullPointerException success) {}
736          }
737      }
738  
739      /**
740 <     * get of returned element of invokeAll(c) throws exception on failed task
740 >     * get of returned element of invokeAll(c) throws
741 >     * ExecutionException on failed task
742       */
743 <    public void testInvokeAll4() {
743 >    public void testInvokeAll4() throws Throwable {
744          ExecutorService e = new ForkJoinPool(1);
745 <        try {
746 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
745 >        try (PoolCleaner cleaner = cleaner(e)) {
746 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
747              l.add(new NPETask());
748 <            List<Future<String>> result = e.invokeAll(l);
749 <            assertEquals(1, result.size());
750 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
751 <                it.next().get();
752 <        } catch(ExecutionException success) {
753 <        } catch (CancellationException success) {
754 <        } catch(Exception ex) {
755 <            ex.printStackTrace();
913 <            unexpectedException();
914 <        } finally {
915 <            joinPool(e);
748 >            List<Future<String>> futures = e.invokeAll(l);
749 >            assertEquals(1, futures.size());
750 >            try {
751 >                futures.get(0).get();
752 >                shouldThrow();
753 >            } catch (ExecutionException success) {
754 >                assertTrue(success.getCause() instanceof NullPointerException);
755 >            }
756          }
757      }
758  
759      /**
760       * invokeAll(c) returns results of all completed tasks in c
761       */
762 <    public void testInvokeAll5() {
762 >    public void testInvokeAll5() throws Throwable {
763          ExecutorService e = new ForkJoinPool(1);
764 <        try {
765 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
764 >        try (PoolCleaner cleaner = cleaner(e)) {
765 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
766              l.add(new StringTask());
767              l.add(new StringTask());
768 <            List<Future<String>> result = e.invokeAll(l);
769 <            assertEquals(2, result.size());
770 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
771 <                assertSame(TEST_STRING, it.next().get());
932 <        } catch (ExecutionException success) {
933 <        } catch (CancellationException success) {
934 <        } catch(Exception ex) {
935 <            ex.printStackTrace();
936 <            unexpectedException();
937 <        } finally {
938 <            joinPool(e);
768 >            List<Future<String>> futures = e.invokeAll(l);
769 >            assertEquals(2, futures.size());
770 >            for (Future<String> future : futures)
771 >                assertSame(TEST_STRING, future.get());
772          }
773      }
774  
942
775      /**
776 <     * timed invokeAny(null) throws NPE
776 >     * timed invokeAny(null) throws NullPointerException
777       */
778 <    public void testTimedInvokeAny1() {
778 >    public void testTimedInvokeAny1() throws Throwable {
779          ExecutorService e = new ForkJoinPool(1);
780 <        try {
781 <            e.invokeAny(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
782 <        } catch (NullPointerException success) {
783 <        } catch(Exception ex) {
784 <            ex.printStackTrace();
953 <            unexpectedException();
954 <        } finally {
955 <            joinPool(e);
780 >        try (PoolCleaner cleaner = cleaner(e)) {
781 >            try {
782 >                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
783 >                shouldThrow();
784 >            } catch (NullPointerException success) {}
785          }
786      }
787  
788      /**
789 <     * timed invokeAny(null time unit) throws NPE
789 >     * timed invokeAny(null time unit) throws NullPointerException
790       */
791 <    public void testTimedInvokeAnyNullTimeUnit() {
791 >    public void testTimedInvokeAnyNullTimeUnit() throws Throwable {
792          ExecutorService e = new ForkJoinPool(1);
793 <        try {
794 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
793 >        try (PoolCleaner cleaner = cleaner(e)) {
794 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
795              l.add(new StringTask());
796 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
797 <        } catch (NullPointerException success) {
798 <        } catch(Exception ex) {
799 <            ex.printStackTrace();
971 <            unexpectedException();
972 <        } finally {
973 <            joinPool(e);
796 >            try {
797 >                e.invokeAny(l, MEDIUM_DELAY_MS, null);
798 >                shouldThrow();
799 >            } catch (NullPointerException success) {}
800          }
801      }
802  
803      /**
804 <     * timed invokeAny(empty collection) throws IAE
804 >     * timed invokeAny(empty collection) throws IllegalArgumentException
805       */
806 <    public void testTimedInvokeAny2() {
806 >    public void testTimedInvokeAny2() throws Throwable {
807          ExecutorService e = new ForkJoinPool(1);
808 <        try {
809 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
810 <        } catch (IllegalArgumentException success) {
811 <        } catch(Exception ex) {
812 <            ex.printStackTrace();
813 <            unexpectedException();
988 <        } finally {
989 <            joinPool(e);
808 >        try (PoolCleaner cleaner = cleaner(e)) {
809 >            try {
810 >                e.invokeAny(new ArrayList<Callable<String>>(),
811 >                            MEDIUM_DELAY_MS, MILLISECONDS);
812 >                shouldThrow();
813 >            } catch (IllegalArgumentException success) {}
814          }
815      }
816  
817      /**
818 <     * timed invokeAny(c) throws NPE if c has null elements
818 >     * timed invokeAny(c) throws NullPointerException if c has null elements
819       */
820 <    public void testTimedInvokeAny3() {
820 >    public void testTimedInvokeAny3() throws Throwable {
821 >        CountDownLatch latch = new CountDownLatch(1);
822          ExecutorService e = new ForkJoinPool(1);
823 <        try {
824 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
825 <            l.add(new StringTask());
823 >        try (PoolCleaner cleaner = cleaner(e)) {
824 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
825 >            l.add(latchAwaitingStringTask(latch));
826              l.add(null);
827 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
828 <        } catch (NullPointerException success) {
829 <        } catch(Exception ex) {
830 <            ex.printStackTrace();
831 <            unexpectedException();
1007 <        } finally {
1008 <            joinPool(e);
827 >            try {
828 >                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
829 >                shouldThrow();
830 >            } catch (NullPointerException success) {}
831 >            latch.countDown();
832          }
833      }
834  
835      /**
836       * timed invokeAny(c) throws ExecutionException if no task completes
837       */
838 <    public void testTimedInvokeAny4() {
838 >    public void testTimedInvokeAny4() throws Throwable {
839          ExecutorService e = new ForkJoinPool(1);
840 <        try {
841 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
840 >        try (PoolCleaner cleaner = cleaner(e)) {
841 >            long startTime = System.nanoTime();
842 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
843              l.add(new NPETask());
844 <            e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
845 <        } catch(ExecutionException success) {
846 <        } catch (CancellationException success) {
847 <        } catch(Exception ex) {
848 <            ex.printStackTrace();
849 <            unexpectedException();
850 <        } finally {
1027 <            joinPool(e);
844 >            try {
845 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
846 >                shouldThrow();
847 >            } catch (ExecutionException success) {
848 >                assertTrue(success.getCause() instanceof NullPointerException);
849 >            }
850 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
851          }
852      }
853  
854      /**
855       * timed invokeAny(c) returns result of some task in c
856       */
857 <    public void testTimedInvokeAny5() {
857 >    public void testTimedInvokeAny5() throws Throwable {
858          ExecutorService e = new ForkJoinPool(1);
859 <        try {
860 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
859 >        try (PoolCleaner cleaner = cleaner(e)) {
860 >            long startTime = System.nanoTime();
861 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
862              l.add(new StringTask());
863              l.add(new StringTask());
864 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
864 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
865              assertSame(TEST_STRING, result);
866 <        } catch (ExecutionException success) {
1043 <        } catch (CancellationException success) {
1044 <        } catch(Exception ex) {
1045 <            ex.printStackTrace();
1046 <            unexpectedException();
1047 <        } finally {
1048 <            joinPool(e);
866 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
867          }
868      }
869  
870      /**
871 <     * timed invokeAll(null) throws NPE
871 >     * timed invokeAll(null) throws NullPointerException
872       */
873 <    public void testTimedInvokeAll1() {
873 >    public void testTimedInvokeAll1() throws Throwable {
874          ExecutorService e = new ForkJoinPool(1);
875 <        try {
876 <            e.invokeAll(null, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
877 <        } catch (NullPointerException success) {
878 <        } catch(Exception ex) {
879 <            ex.printStackTrace();
1062 <            unexpectedException();
1063 <        } finally {
1064 <            joinPool(e);
875 >        try (PoolCleaner cleaner = cleaner(e)) {
876 >            try {
877 >                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
878 >                shouldThrow();
879 >            } catch (NullPointerException success) {}
880          }
881      }
882  
883      /**
884 <     * timed invokeAll(null time unit) throws NPE
884 >     * timed invokeAll(null time unit) throws NullPointerException
885       */
886 <    public void testTimedInvokeAllNullTimeUnit() {
886 >    public void testTimedInvokeAllNullTimeUnit() throws Throwable {
887          ExecutorService e = new ForkJoinPool(1);
888 <        try {
889 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
888 >        try (PoolCleaner cleaner = cleaner(e)) {
889 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
890              l.add(new StringTask());
891 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
892 <        } catch (NullPointerException success) {
893 <        } catch(Exception ex) {
894 <            ex.printStackTrace();
1080 <            unexpectedException();
1081 <        } finally {
1082 <            joinPool(e);
891 >            try {
892 >                e.invokeAll(l, MEDIUM_DELAY_MS, null);
893 >                shouldThrow();
894 >            } catch (NullPointerException success) {}
895          }
896      }
897  
898      /**
899       * timed invokeAll(empty collection) returns empty collection
900       */
901 <    public void testTimedInvokeAll2() {
901 >    public void testTimedInvokeAll2() throws InterruptedException {
902          ExecutorService e = new ForkJoinPool(1);
903 <        try {
904 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
903 >        try (PoolCleaner cleaner = cleaner(e)) {
904 >            List<Future<String>> r
905 >                = e.invokeAll(new ArrayList<Callable<String>>(),
906 >                              MEDIUM_DELAY_MS, MILLISECONDS);
907              assertTrue(r.isEmpty());
1094        } catch(Exception ex) {
1095            ex.printStackTrace();
1096            unexpectedException();
1097        } finally {
1098            joinPool(e);
908          }
909      }
910  
911      /**
912 <     * timed invokeAll(c) throws NPE if c has null elements
912 >     * timed invokeAll(c) throws NullPointerException if c has null elements
913       */
914 <    public void testTimedInvokeAll3() {
914 >    public void testTimedInvokeAll3() throws InterruptedException {
915          ExecutorService e = new ForkJoinPool(1);
916 <        try {
917 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
916 >        try (PoolCleaner cleaner = cleaner(e)) {
917 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
918              l.add(new StringTask());
919              l.add(null);
920 <            e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
921 <        } catch (NullPointerException success) {
922 <        } catch(Exception ex) {
923 <            ex.printStackTrace();
1115 <            unexpectedException();
1116 <        } finally {
1117 <            joinPool(e);
920 >            try {
921 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
922 >                shouldThrow();
923 >            } catch (NullPointerException success) {}
924          }
925      }
926  
927      /**
928       * get of returned element of invokeAll(c) throws exception on failed task
929       */
930 <    public void testTimedInvokeAll4() {
930 >    public void testTimedInvokeAll4() throws Throwable {
931          ExecutorService e = new ForkJoinPool(1);
932 <        try {
933 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
932 >        try (PoolCleaner cleaner = cleaner(e)) {
933 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
934              l.add(new NPETask());
935 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
936 <            assertEquals(1, result.size());
937 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
938 <                it.next().get();
939 <        } catch(ExecutionException success) {
940 <        } catch (CancellationException success) {
941 <        } catch(Exception ex) {
942 <            ex.printStackTrace();
943 <            unexpectedException();
1138 <        } finally {
1139 <            joinPool(e);
935 >            List<Future<String>> futures
936 >                = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
937 >            assertEquals(1, futures.size());
938 >            try {
939 >                futures.get(0).get();
940 >                shouldThrow();
941 >            } catch (ExecutionException success) {
942 >                assertTrue(success.getCause() instanceof NullPointerException);
943 >            }
944          }
945      }
946  
947      /**
948       * timed invokeAll(c) returns results of all completed tasks in c
949       */
950 <    public void testTimedInvokeAll5() {
951 <        ExecutorService e = new ForkJoinPool(1);
952 <        try {
953 <            ArrayList<Callable<String>> l = new ArrayList<Callable<String>>();
950 >    public void testTimedInvokeAll5() throws Throwable {
951 >        ForkJoinPool e = new ForkJoinPool(1);
952 >        try (PoolCleaner cleaner = cleaner(e)) {
953 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
954              l.add(new StringTask());
955              l.add(new StringTask());
956 <            List<Future<String>> result = e.invokeAll(l, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
957 <            assertEquals(2, result.size());
958 <            for (Iterator<Future<String>> it = result.iterator(); it.hasNext();)
959 <                assertSame(TEST_STRING, it.next().get());
960 <        } catch (ExecutionException success) {
1157 <        } catch (CancellationException success) {
1158 <        } catch(Exception ex) {
1159 <            ex.printStackTrace();
1160 <            unexpectedException();
1161 <        } finally {
1162 <            joinPool(e);
956 >            List<Future<String>> futures
957 >                = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
958 >            assertEquals(2, futures.size());
959 >            for (Future<String> future : futures)
960 >                assertSame(TEST_STRING, future.get());
961          }
962      }
963  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines