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.35 by dl, Fri Nov 19 00:20:47 2010 UTC vs.
Revision 1.53 by jsr166, Wed Dec 31 16:44:01 2014 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 junit.framework.*;
# Line 10 | Line 10 | import java.util.Collection;
10   import java.util.List;
11   import java.util.concurrent.Executors;
12   import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.AbstractExecutorService;
13   import java.util.concurrent.CountDownLatch;
14   import java.util.concurrent.Callable;
15   import java.util.concurrent.Future;
16   import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.CancellationException;
17   import java.util.concurrent.RejectedExecutionException;
18   import java.util.concurrent.ForkJoinPool;
19   import java.util.concurrent.ForkJoinTask;
20   import java.util.concurrent.ForkJoinWorkerThread;
21   import java.util.concurrent.RecursiveTask;
22 < import java.util.concurrent.TimeUnit;
22 > import java.util.concurrent.atomic.AtomicBoolean;
23   import java.util.concurrent.locks.ReentrantLock;
24   import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import java.security.AccessControlException;
28 < import java.security.Policy;
25 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
26   import java.security.PrivilegedAction;
27   import java.security.PrivilegedExceptionAction;
28  
# Line 38 | Line 35 | public class ForkJoinPoolTest extends JS
35          return new TestSuite(ForkJoinPoolTest.class);
36      }
37  
38 <    /**
38 >    /*
39       * Testing coverage notes:
40       *
41       * 1. shutdown and related methods are tested via super.joinPool.
# Line 106 | Line 103 | public class ForkJoinPoolTest extends JS
103      static final class FibTask extends RecursiveTask<Integer> {
104          final int number;
105          FibTask(int n) { number = n; }
106 <        public Integer compute() {
106 >        protected Integer compute() {
107              int n = number;
108              if (n <= 1)
109                  return n;
# Line 134 | Line 131 | public class ForkJoinPoolTest extends JS
131              this.locker = locker;
132              this.lock = lock;
133          }
134 <        public Integer compute() {
134 >        protected Integer compute() {
135              int n;
136              LockingFibTask f1 = null;
137              LockingFibTask f2 = null;
# Line 164 | Line 161 | public class ForkJoinPoolTest extends JS
161          try {
162              assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
163                         p.getFactory());
167            assertTrue(p.isQuiescent());
164              assertFalse(p.getAsyncMode());
165              assertEquals(0, p.getActiveThreadCount());
166              assertEquals(0, p.getStealCount());
# Line 199 | Line 195 | public class ForkJoinPoolTest extends JS
195          } catch (NullPointerException success) {}
196      }
197  
202
198      /**
199       * getParallelism returns size set in constructor
200       */
# Line 227 | Line 222 | public class ForkJoinPoolTest extends JS
222      }
223  
224      /**
225 +     * awaitTermination on a non-shutdown pool times out
226 +     */
227 +    public void testAwaitTermination_timesOut() throws InterruptedException {
228 +        ForkJoinPool p = new ForkJoinPool(1);
229 +        assertFalse(p.isTerminated());
230 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
231 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
232 +        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
233 +        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
234 +        assertFalse(p.awaitTermination(0L, NANOSECONDS));
235 +        assertFalse(p.awaitTermination(0L, MILLISECONDS));
236 +        long timeoutNanos = 999999L;
237 +        long startTime = System.nanoTime();
238 +        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
239 +        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
240 +        assertFalse(p.isTerminated());
241 +        startTime = System.nanoTime();
242 +        long timeoutMillis = timeoutMillis();
243 +        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
244 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
245 +        assertFalse(p.isTerminated());
246 +        p.shutdown();
247 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
248 +        assertTrue(p.isTerminated());
249 +    }
250 +
251 +    /**
252       * setUncaughtExceptionHandler changes handler for uncaught exceptions.
253       *
254       * Additionally tests: Overriding ForkJoinWorkerThread.onStart
# Line 243 | Line 265 | public class ForkJoinPoolTest extends JS
265                                            eh, false);
266          try {
267              assertSame(eh, p.getUncaughtExceptionHandler());
268 <            p.execute(new FibTask(8));
269 <            assertTrue(uehInvoked.await(MEDIUM_DELAY_MS, MILLISECONDS));
268 >            try {
269 >                p.execute(new FibTask(8));
270 >                assertTrue(uehInvoked.await(MEDIUM_DELAY_MS, MILLISECONDS));
271 >            } catch (RejectedExecutionException ok) {
272 >            }
273          } finally {
274              p.shutdownNow(); // failure might have prevented processing task
275              joinPool(p);
# Line 252 | Line 277 | public class ForkJoinPoolTest extends JS
277      }
278  
279      /**
280 <     * After invoking a single task, isQuiescent is true,
281 <     * queues are empty, threads are not active, and
282 <     * construction parameters continue to hold
280 >     * After invoking a single task, isQuiescent eventually becomes
281 >     * true, at which time queues are empty, threads are not active,
282 >     * the task has completed successfully, and construction
283 >     * parameters continue to hold
284       */
285 <    public void testisQuiescent() throws InterruptedException {
285 >    public void testIsQuiescent() throws Exception {
286          ForkJoinPool p = new ForkJoinPool(2);
287          try {
288              assertTrue(p.isQuiescent());
289 <            p.invoke(new FibTask(20));
289 >            long startTime = System.nanoTime();
290 >            FibTask f = new FibTask(20);
291 >            p.invoke(f);
292              assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
293                         p.getFactory());
294 <            Thread.sleep(SMALL_DELAY_MS);
294 >            while (! p.isQuiescent()) {
295 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
296 >                    throw new AssertionFailedError("timed out");
297 >                assertFalse(p.getAsyncMode());
298 >                assertFalse(p.isShutdown());
299 >                assertFalse(p.isTerminating());
300 >                assertFalse(p.isTerminated());
301 >                Thread.yield();
302 >            }
303 >
304              assertTrue(p.isQuiescent());
305              assertFalse(p.getAsyncMode());
306              assertEquals(0, p.getActiveThreadCount());
# Line 273 | Line 310 | public class ForkJoinPoolTest extends JS
310              assertFalse(p.isShutdown());
311              assertFalse(p.isTerminating());
312              assertFalse(p.isTerminated());
313 +            assertTrue(f.isDone());
314 +            assertEquals(6765, (int) f.get());
315          } finally {
316              joinPool(p);
317          }
# Line 328 | Line 367 | public class ForkJoinPoolTest extends JS
367       * pollSubmission returns unexecuted submitted task, if present
368       */
369      public void testPollSubmission() {
370 +        final CountDownLatch done = new CountDownLatch(1);
371          SubFJP p = new SubFJP();
372          try {
373 <            ForkJoinTask a = p.submit(new ShortRunnable());
374 <            ForkJoinTask b = p.submit(new ShortRunnable());
375 <            ForkJoinTask c = p.submit(new ShortRunnable());
373 >            ForkJoinTask a = p.submit(awaiter(done));
374 >            ForkJoinTask b = p.submit(awaiter(done));
375 >            ForkJoinTask c = p.submit(awaiter(done));
376              ForkJoinTask r = p.pollSubmission();
377              assertTrue(r == a || r == b || r == c);
378              assertFalse(r.isDone());
379          } finally {
380 +            done.countDown();
381              joinPool(p);
382          }
383      }
# Line 345 | Line 386 | public class ForkJoinPoolTest extends JS
386       * drainTasksTo transfers unexecuted submitted tasks, if present
387       */
388      public void testDrainTasksTo() {
389 +        final CountDownLatch done = new CountDownLatch(1);
390          SubFJP p = new SubFJP();
391          try {
392 <            ForkJoinTask a = p.submit(new ShortRunnable());
393 <            ForkJoinTask b = p.submit(new ShortRunnable());
394 <            ForkJoinTask c = p.submit(new ShortRunnable());
392 >            ForkJoinTask a = p.submit(awaiter(done));
393 >            ForkJoinTask b = p.submit(awaiter(done));
394 >            ForkJoinTask c = p.submit(awaiter(done));
395              ArrayList<ForkJoinTask> al = new ArrayList();
396              p.drainTasksTo(al);
397              assertTrue(al.size() > 0);
# Line 358 | Line 400 | public class ForkJoinPoolTest extends JS
400                  assertFalse(r.isDone());
401              }
402          } finally {
403 +            done.countDown();
404              joinPool(p);
405          }
406      }
407  
365
408      // FJ Versions of AbstractExecutorService tests
409  
410      /**
# Line 371 | Line 413 | public class ForkJoinPoolTest extends JS
413      public void testExecuteRunnable() throws Throwable {
414          ExecutorService e = new ForkJoinPool(1);
415          try {
416 <            TrackedRunnable task = trackedRunnable(SHORT_DELAY_MS);
417 <            assertFalse(task.isDone());
418 <            Future<?> future = e.submit(task);
416 >            final AtomicBoolean done = new AtomicBoolean(false);
417 >            Future<?> future = e.submit(new CheckedRunnable() {
418 >                public void realRun() {
419 >                    done.set(true);
420 >                }});
421              assertNull(future.get());
422 <            assertTrue(task.isDone());
422 >            assertNull(future.get(0, MILLISECONDS));
423 >            assertTrue(done.get());
424 >            assertTrue(future.isDone());
425              assertFalse(future.isCancelled());
426          } finally {
427              joinPool(e);
428          }
429      }
430  
385
431      /**
432       * Completed submit(callable) returns result
433       */
# Line 432 | Line 477 | public class ForkJoinPoolTest extends JS
477       * A submitted privileged action runs to completion
478       */
479      public void testSubmitPrivilegedAction() throws Exception {
480 +        final Callable callable = Executors.callable(new PrivilegedAction() {
481 +                public Object run() { return TEST_STRING; }});
482          Runnable r = new CheckedRunnable() {
483 <            public void realRun() throws Exception {
484 <                ExecutorService e = new ForkJoinPool(1);
485 <                Future future = e.submit(Executors.callable(new PrivilegedAction() {
486 <                    public Object run() {
440 <                        return TEST_STRING;
441 <                    }}));
442 <
483 >        public void realRun() throws Exception {
484 >            ExecutorService e = new ForkJoinPool(1);
485 >            try {
486 >                Future future = e.submit(callable);
487                  assertSame(TEST_STRING, future.get());
488 <            }};
488 >            } finally {
489 >                joinPool(e);
490 >            }
491 >        }};
492  
493 <        runWithPermissions(r,
447 <                           new RuntimePermission("modifyThread"));
493 >        runWithPermissions(r, new RuntimePermission("modifyThread"));
494      }
495  
496      /**
497       * A submitted privileged exception action runs to completion
498       */
499      public void testSubmitPrivilegedExceptionAction() throws Exception {
500 +        final Callable callable =
501 +            Executors.callable(new PrivilegedExceptionAction() {
502 +                public Object run() { return TEST_STRING; }});
503          Runnable r = new CheckedRunnable() {
504 <            public void realRun() throws Exception {
505 <                ExecutorService e = new ForkJoinPool(1);
506 <                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
507 <                    public Object run() {
459 <                        return TEST_STRING;
460 <                    }}));
461 <
504 >        public void realRun() throws Exception {
505 >            ExecutorService e = new ForkJoinPool(1);
506 >            try {
507 >                Future future = e.submit(callable);
508                  assertSame(TEST_STRING, future.get());
509 <            }};
509 >            } finally {
510 >                joinPool(e);
511 >            }
512 >        }};
513  
514          runWithPermissions(r, new RuntimePermission("modifyThread"));
515      }
# Line 469 | Line 518 | public class ForkJoinPoolTest extends JS
518       * A submitted failed privileged exception action reports exception
519       */
520      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
521 +        final Callable callable =
522 +            Executors.callable(new PrivilegedExceptionAction() {
523 +                public Object run() { throw new IndexOutOfBoundsException(); }});
524          Runnable r = new CheckedRunnable() {
525 <            public void realRun() throws Exception {
526 <                ExecutorService e = new ForkJoinPool(1);
527 <                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
528 <                    public Object run() throws Exception {
477 <                        throw new IndexOutOfBoundsException();
478 <                    }}));
479 <
525 >        public void realRun() throws Exception {
526 >            ExecutorService e = new ForkJoinPool(1);
527 >            try {
528 >                Future future = e.submit(callable);
529                  try {
530                      future.get();
531                      shouldThrow();
532                  } catch (ExecutionException success) {
533                      assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
534 <                }}};
534 >                }
535 >            } finally {
536 >                joinPool(e);
537 >            }
538 >        }};
539  
540          runWithPermissions(r, new RuntimePermission("modifyThread"));
541      }
# Line 501 | Line 554 | public class ForkJoinPoolTest extends JS
554          }
555      }
556  
504
557      /**
558       * submit(null callable) throws NullPointerException
559       */
# Line 516 | Line 568 | public class ForkJoinPoolTest extends JS
568          }
569      }
570  
519
571      /**
572       * submit(callable).get() throws InterruptedException if interrupted
573       */
# Line 554 | Line 605 | public class ForkJoinPoolTest extends JS
605          ForkJoinPool p = new ForkJoinPool(1);
606          try {
607              p.submit(new Callable() {
608 <                public Object call() {
609 <                    int i = 5/0;
559 <                    return Boolean.TRUE;
560 <                }}).get();
608 >                public Object call() { throw new ArithmeticException(); }})
609 >                .get();
610              shouldThrow();
611          } catch (ExecutionException success) {
612              assertTrue(success.getCause() instanceof ArithmeticException);
# Line 745 | Line 794 | public class ForkJoinPoolTest extends JS
794          }
795      }
796  
748
797      /**
798       * timed invokeAny(null) throws NullPointerException
799       */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines