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.57 by jsr166, Sat Oct 3 16:57:25 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 junit.framework.*;
7 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
8 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
9 >
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;
11 import java.util.concurrent.Executors;
12 import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.AbstractExecutorService;
14 import java.util.concurrent.CountDownLatch;
15   import java.util.concurrent.Callable;
16 < import java.util.concurrent.Future;
16 > import java.util.concurrent.CountDownLatch;
17   import java.util.concurrent.ExecutionException;
18 < import java.util.concurrent.CancellationException;
19 < import java.util.concurrent.RejectedExecutionException;
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.TimeUnit;
25 > import java.util.concurrent.RejectedExecutionException;
26 > import java.util.concurrent.atomic.AtomicBoolean;
27   import java.util.concurrent.locks.ReentrantLock;
28 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
29 < import java.security.AccessControlException;
30 < import java.security.Policy;
31 < import java.security.PrivilegedAction;
30 < import java.security.PrivilegedExceptionAction;
28 >
29 > import junit.framework.AssertionFailedError;
30 > import junit.framework.Test;
31 > import junit.framework.TestSuite;
32  
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.
# Line 106 | Line 107 | public class ForkJoinPoolTest extends JS
107      static final class FibTask extends RecursiveTask<Integer> {
108          final int number;
109          FibTask(int n) { number = n; }
110 <        public Integer compute() {
110 >        protected Integer compute() {
111              int n = number;
112              if (n <= 1)
113                  return n;
# Line 134 | Line 135 | public class ForkJoinPoolTest extends JS
135              this.locker = locker;
136              this.lock = lock;
137          }
138 <        public Integer compute() {
138 >        protected Integer compute() {
139              int n;
140              LockingFibTask f1 = null;
141              LockingFibTask f2 = null;
# Line 164 | Line 165 | public class ForkJoinPoolTest extends JS
165          try {
166              assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
167                         p.getFactory());
167            assertTrue(p.isQuiescent());
168              assertFalse(p.getAsyncMode());
169              assertEquals(0, p.getActiveThreadCount());
170              assertEquals(0, p.getStealCount());
# Line 199 | Line 199 | public class ForkJoinPoolTest extends JS
199          } catch (NullPointerException success) {}
200      }
201  
202
202      /**
203       * getParallelism returns size set in constructor
204       */
# Line 227 | Line 226 | public class ForkJoinPoolTest extends JS
226      }
227  
228      /**
229 +     * awaitTermination on a non-shutdown pool times out
230 +     */
231 +    public void testAwaitTermination_timesOut() throws InterruptedException {
232 +        ForkJoinPool p = new ForkJoinPool(1);
233 +        assertFalse(p.isTerminated());
234 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
235 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
236 +        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
237 +        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
238 +        assertFalse(p.awaitTermination(0L, NANOSECONDS));
239 +        assertFalse(p.awaitTermination(0L, MILLISECONDS));
240 +        long timeoutNanos = 999999L;
241 +        long startTime = System.nanoTime();
242 +        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
243 +        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
244 +        assertFalse(p.isTerminated());
245 +        startTime = System.nanoTime();
246 +        long timeoutMillis = timeoutMillis();
247 +        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
248 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
249 +        assertFalse(p.isTerminated());
250 +        p.shutdown();
251 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
252 +        assertTrue(p.isTerminated());
253 +    }
254 +
255 +    /**
256       * setUncaughtExceptionHandler changes handler for uncaught exceptions.
257       *
258       * Additionally tests: Overriding ForkJoinWorkerThread.onStart
# Line 243 | Line 269 | public class ForkJoinPoolTest extends JS
269                                            eh, false);
270          try {
271              assertSame(eh, p.getUncaughtExceptionHandler());
272 <            p.execute(new FibTask(8));
273 <            assertTrue(uehInvoked.await(MEDIUM_DELAY_MS, MILLISECONDS));
272 >            try {
273 >                p.execute(new FibTask(8));
274 >                assertTrue(uehInvoked.await(MEDIUM_DELAY_MS, MILLISECONDS));
275 >            } catch (RejectedExecutionException ok) {
276 >            }
277          } finally {
278              p.shutdownNow(); // failure might have prevented processing task
279              joinPool(p);
# Line 252 | Line 281 | public class ForkJoinPoolTest extends JS
281      }
282  
283      /**
284 <     * After invoking a single task, isQuiescent is true,
285 <     * queues are empty, threads are not active, and
286 <     * construction parameters continue to hold
284 >     * After invoking a single task, isQuiescent eventually becomes
285 >     * true, at which time queues are empty, threads are not active,
286 >     * the task has completed successfully, and construction
287 >     * parameters continue to hold
288       */
289 <    public void testisQuiescent() throws InterruptedException {
289 >    public void testIsQuiescent() throws Exception {
290          ForkJoinPool p = new ForkJoinPool(2);
291          try {
292              assertTrue(p.isQuiescent());
293 <            p.invoke(new FibTask(20));
293 >            long startTime = System.nanoTime();
294 >            FibTask f = new FibTask(20);
295 >            p.invoke(f);
296              assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory,
297                         p.getFactory());
298 <            Thread.sleep(SMALL_DELAY_MS);
298 >            while (! p.isQuiescent()) {
299 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
300 >                    throw new AssertionFailedError("timed out");
301 >                assertFalse(p.getAsyncMode());
302 >                assertFalse(p.isShutdown());
303 >                assertFalse(p.isTerminating());
304 >                assertFalse(p.isTerminated());
305 >                Thread.yield();
306 >            }
307 >
308              assertTrue(p.isQuiescent());
309              assertFalse(p.getAsyncMode());
310              assertEquals(0, p.getActiveThreadCount());
# Line 273 | Line 314 | public class ForkJoinPoolTest extends JS
314              assertFalse(p.isShutdown());
315              assertFalse(p.isTerminating());
316              assertFalse(p.isTerminated());
317 +            assertTrue(f.isDone());
318 +            assertEquals(6765, (int) f.get());
319          } finally {
320              joinPool(p);
321          }
# Line 328 | Line 371 | public class ForkJoinPoolTest extends JS
371       * pollSubmission returns unexecuted submitted task, if present
372       */
373      public void testPollSubmission() {
374 +        final CountDownLatch done = new CountDownLatch(1);
375          SubFJP p = new SubFJP();
376          try {
377 <            ForkJoinTask a = p.submit(new ShortRunnable());
378 <            ForkJoinTask b = p.submit(new ShortRunnable());
379 <            ForkJoinTask c = p.submit(new ShortRunnable());
377 >            ForkJoinTask a = p.submit(awaiter(done));
378 >            ForkJoinTask b = p.submit(awaiter(done));
379 >            ForkJoinTask c = p.submit(awaiter(done));
380              ForkJoinTask r = p.pollSubmission();
381              assertTrue(r == a || r == b || r == c);
382              assertFalse(r.isDone());
383          } finally {
384 +            done.countDown();
385              joinPool(p);
386          }
387      }
# Line 345 | Line 390 | public class ForkJoinPoolTest extends JS
390       * drainTasksTo transfers unexecuted submitted tasks, if present
391       */
392      public void testDrainTasksTo() {
393 +        final CountDownLatch done = new CountDownLatch(1);
394          SubFJP p = new SubFJP();
395          try {
396 <            ForkJoinTask a = p.submit(new ShortRunnable());
397 <            ForkJoinTask b = p.submit(new ShortRunnable());
398 <            ForkJoinTask c = p.submit(new ShortRunnable());
396 >            ForkJoinTask a = p.submit(awaiter(done));
397 >            ForkJoinTask b = p.submit(awaiter(done));
398 >            ForkJoinTask c = p.submit(awaiter(done));
399              ArrayList<ForkJoinTask> al = new ArrayList();
400              p.drainTasksTo(al);
401              assertTrue(al.size() > 0);
# Line 358 | Line 404 | public class ForkJoinPoolTest extends JS
404                  assertFalse(r.isDone());
405              }
406          } finally {
407 +            done.countDown();
408              joinPool(p);
409          }
410      }
411  
365
412      // FJ Versions of AbstractExecutorService tests
413  
414      /**
# Line 371 | Line 417 | public class ForkJoinPoolTest extends JS
417      public void testExecuteRunnable() throws Throwable {
418          ExecutorService e = new ForkJoinPool(1);
419          try {
420 <            TrackedRunnable task = trackedRunnable(SHORT_DELAY_MS);
421 <            assertFalse(task.isDone());
422 <            Future<?> future = e.submit(task);
420 >            final AtomicBoolean done = new AtomicBoolean(false);
421 >            Future<?> future = e.submit(new CheckedRunnable() {
422 >                public void realRun() {
423 >                    done.set(true);
424 >                }});
425              assertNull(future.get());
426 <            assertTrue(task.isDone());
426 >            assertNull(future.get(0, MILLISECONDS));
427 >            assertTrue(done.get());
428 >            assertTrue(future.isDone());
429              assertFalse(future.isCancelled());
430          } finally {
431              joinPool(e);
432          }
433      }
434  
385
435      /**
436       * Completed submit(callable) returns result
437       */
# Line 432 | Line 481 | public class ForkJoinPoolTest extends JS
481       * A submitted privileged action runs to completion
482       */
483      public void testSubmitPrivilegedAction() throws Exception {
484 +        final Callable callable = Executors.callable(new PrivilegedAction() {
485 +                public Object run() { return TEST_STRING; }});
486          Runnable r = new CheckedRunnable() {
487 <            public void realRun() throws Exception {
488 <                ExecutorService e = new ForkJoinPool(1);
489 <                Future future = e.submit(Executors.callable(new PrivilegedAction() {
490 <                    public Object run() {
440 <                        return TEST_STRING;
441 <                    }}));
442 <
487 >        public void realRun() throws Exception {
488 >            ExecutorService e = new ForkJoinPool(1);
489 >            try {
490 >                Future future = e.submit(callable);
491                  assertSame(TEST_STRING, future.get());
492 <            }};
492 >            } finally {
493 >                joinPool(e);
494 >            }
495 >        }};
496  
497 <        runWithPermissions(r,
447 <                           new RuntimePermission("modifyThread"));
497 >        runWithPermissions(r, new RuntimePermission("modifyThread"));
498      }
499  
500      /**
501       * A submitted privileged exception action runs to completion
502       */
503      public void testSubmitPrivilegedExceptionAction() throws Exception {
504 +        final Callable callable =
505 +            Executors.callable(new PrivilegedExceptionAction() {
506 +                public Object run() { return TEST_STRING; }});
507          Runnable r = new CheckedRunnable() {
508 <            public void realRun() throws Exception {
509 <                ExecutorService e = new ForkJoinPool(1);
510 <                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
511 <                    public Object run() {
459 <                        return TEST_STRING;
460 <                    }}));
461 <
508 >        public void realRun() throws Exception {
509 >            ExecutorService e = new ForkJoinPool(1);
510 >            try {
511 >                Future future = e.submit(callable);
512                  assertSame(TEST_STRING, future.get());
513 <            }};
513 >            } finally {
514 >                joinPool(e);
515 >            }
516 >        }};
517  
518          runWithPermissions(r, new RuntimePermission("modifyThread"));
519      }
# Line 469 | Line 522 | public class ForkJoinPoolTest extends JS
522       * A submitted failed privileged exception action reports exception
523       */
524      public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
525 +        final Callable callable =
526 +            Executors.callable(new PrivilegedExceptionAction() {
527 +                public Object run() { throw new IndexOutOfBoundsException(); }});
528          Runnable r = new CheckedRunnable() {
529 <            public void realRun() throws Exception {
530 <                ExecutorService e = new ForkJoinPool(1);
531 <                Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
532 <                    public Object run() throws Exception {
477 <                        throw new IndexOutOfBoundsException();
478 <                    }}));
479 <
529 >        public void realRun() throws Exception {
530 >            ExecutorService e = new ForkJoinPool(1);
531 >            try {
532 >                Future future = e.submit(callable);
533                  try {
534                      future.get();
535                      shouldThrow();
536                  } catch (ExecutionException success) {
537                      assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
538 <                }}};
538 >                }
539 >            } finally {
540 >                joinPool(e);
541 >            }
542 >        }};
543  
544          runWithPermissions(r, new RuntimePermission("modifyThread"));
545      }
# Line 501 | Line 558 | public class ForkJoinPoolTest extends JS
558          }
559      }
560  
504
561      /**
562       * submit(null callable) throws NullPointerException
563       */
# Line 516 | Line 572 | public class ForkJoinPoolTest extends JS
572          }
573      }
574  
519
575      /**
576       * submit(callable).get() throws InterruptedException if interrupted
577       */
# Line 554 | Line 609 | public class ForkJoinPoolTest extends JS
609          ForkJoinPool p = new ForkJoinPool(1);
610          try {
611              p.submit(new Callable() {
612 <                public Object call() {
613 <                    int i = 5/0;
559 <                    return Boolean.TRUE;
560 <                }}).get();
612 >                public Object call() { throw new ArithmeticException(); }})
613 >                .get();
614              shouldThrow();
615          } catch (ExecutionException success) {
616              assertTrue(success.getCause() instanceof ArithmeticException);
# Line 745 | Line 798 | public class ForkJoinPoolTest extends JS
798          }
799      }
800  
748
801      /**
802       * timed invokeAny(null) throws NullPointerException
803       */
# Line 929 | Line 981 | public class ForkJoinPoolTest extends JS
981       * timed invokeAll(c) returns results of all completed tasks in c
982       */
983      public void testTimedInvokeAll5() throws Throwable {
984 <        ExecutorService e = new ForkJoinPool(1);
985 <        try {
984 >        try (PoolCloser<ForkJoinPool> poolCloser
985 >             = new PoolCloser(new ForkJoinPool(1))) {
986 >            ForkJoinPool e = poolCloser.pool;
987              List<Callable<String>> l = new ArrayList<Callable<String>>();
988              l.add(new StringTask());
989              l.add(new StringTask());
990              List<Future<String>> futures
991 <                = e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
991 >                = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
992              assertEquals(2, futures.size());
993              for (Future<String> future : futures)
994                  assertSame(TEST_STRING, future.get());
942        } finally {
943            joinPool(e);
995          }
996      }
997  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines