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

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.70 by jsr166, Sun Nov 21 19:04:45 2010 UTC vs.
Revision 1.104 by dl, Thu Mar 21 00:26:43 2013 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10 + import java.io.ByteArrayInputStream;
11 + import java.io.ByteArrayOutputStream;
12 + import java.io.ObjectInputStream;
13 + import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.lang.reflect.Method;
17 + import java.util.ArrayList;
18 + import java.util.Arrays;
19 + import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22 + import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 61 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 134 | Line 148 | public class JSR166TestCase extends Test
148      }
149  
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 166 | Line 182 | public class JSR166TestCase extends Test
182          return suite;
183      }
184  
185 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216       * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        return newTestSuite(
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221              ForkJoinPoolTest.suite(),
222              ForkJoinTaskTest.suite(),
223              RecursiveActionTest.suite(),
# Line 235 | Line 282 | public class JSR166TestCase extends Test
282              TreeSetTest.suite(),
283              TreeSubMapTest.suite(),
284              TreeSubSetTest.suite());
285 +
286 +        // Java8+ test classes
287 +        if (atLeastJava8()) {
288 +            String[] java8TestClassNames = {
289 +                "CompletableFutureTest",
290 +                "CountedCompleterTest",
291 +                "DoubleAccumulatorTest",
292 +                "DoubleAdderTest",
293 +                "ForkJoinPool8Test",
294 +                "LongAccumulatorTest",
295 +                "LongAdderTest",
296 +                "StampedLockTest",
297 +            };
298 +            addNamedTestClasses(suite, java8TestClassNames);
299 +        }
300 +
301 +        return suite;
302      }
303  
304  
# Line 252 | Line 316 | public class JSR166TestCase extends Test
316          return 50;
317      }
318  
255
319      /**
320       * Sets delays as multiples of SHORT_DELAY.
321       */
# Line 260 | Line 323 | public class JSR166TestCase extends Test
323          SHORT_DELAY_MS = getShortDelay();
324          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
325          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
326 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
326 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
327 >    }
328 >
329 >    /**
330 >     * Returns a timeout in milliseconds to be used in tests that
331 >     * verify that operations block or time out.
332 >     */
333 >    long timeoutMillis() {
334 >        return SHORT_DELAY_MS / 4;
335 >    }
336 >
337 >    /**
338 >     * Returns a new Date instance representing a time delayMillis
339 >     * milliseconds in the future.
340 >     */
341 >    Date delayedDate(long delayMillis) {
342 >        return new Date(System.currentTimeMillis() + delayMillis);
343      }
344  
345      /**
# Line 284 | Line 363 | public class JSR166TestCase extends Test
363      }
364  
365      /**
366 +     * Extra checks that get done for all test cases.
367 +     *
368       * Triggers test case failure if any thread assertions have failed,
369       * by rethrowing, in the test harness thread, any exception recorded
370       * earlier by threadRecordFailure.
371 +     *
372 +     * Triggers test case failure if interrupt status is set in the main thread.
373       */
374      public void tearDown() throws Exception {
375          Throwable t = threadFailure.getAndSet(null);
# Line 304 | Line 387 | public class JSR166TestCase extends Test
387                  throw afe;
388              }
389          }
390 +
391 +        if (Thread.interrupted())
392 +            throw new AssertionFailedError("interrupt status set in main thread");
393 +
394 +        checkForkJoinPoolThreadLeaks();
395 +    }
396 +
397 +    /**
398 +     * Find missing try { ... } finally { joinPool(e); }
399 +     */
400 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
401 +        Thread[] survivors = new Thread[5];
402 +        int count = Thread.enumerate(survivors);
403 +        for (int i = 0; i < count; i++) {
404 +            Thread thread = survivors[i];
405 +            String name = thread.getName();
406 +            if (name.startsWith("ForkJoinPool-")) {
407 +                // give thread some time to terminate
408 +                thread.join(LONG_DELAY_MS);
409 +                if (!thread.isAlive()) continue;
410 +                thread.stop();
411 +                throw new AssertionFailedError
412 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
413 +                                   toString(), name));
414 +            }
415 +        }
416      }
417  
418      /**
# Line 435 | Line 544 | public class JSR166TestCase extends Test
544          else {
545              AssertionFailedError afe =
546                  new AssertionFailedError("unexpected exception: " + t);
547 <            t.initCause(t);
547 >            afe.initCause(t);
548              throw afe;
549          }
550      }
551  
552      /**
553 +     * Delays, via Thread.sleep, for the given millisecond delay, but
554 +     * if the sleep is shorter than specified, may re-sleep or yield
555 +     * until time elapses.
556 +     */
557 +    static void delay(long millis) throws InterruptedException {
558 +        long startTime = System.nanoTime();
559 +        long ns = millis * 1000 * 1000;
560 +        for (;;) {
561 +            if (millis > 0L)
562 +                Thread.sleep(millis);
563 +            else // too short to sleep
564 +                Thread.yield();
565 +            long d = ns - (System.nanoTime() - startTime);
566 +            if (d > 0L)
567 +                millis = d / (1000 * 1000);
568 +            else
569 +                break;
570 +        }
571 +    }
572 +
573 +    /**
574       * Waits out termination of a thread pool or fails doing so.
575       */
576 <    public void joinPool(ExecutorService exec) {
576 >    void joinPool(ExecutorService exec) {
577          try {
578              exec.shutdown();
579              assertTrue("ExecutorService did not terminate in a timely manner",
580 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
580 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
581          } catch (SecurityException ok) {
582              // Allowed in case test doesn't have privs
583          } catch (InterruptedException ie) {
# Line 455 | Line 585 | public class JSR166TestCase extends Test
585          }
586      }
587  
588 +    /**
589 +     * A debugging tool to print all stack traces, as jstack does.
590 +     */
591 +    static void printAllStackTraces() {
592 +        for (ThreadInfo info :
593 +                 ManagementFactory.getThreadMXBean()
594 +                 .dumpAllThreads(true, true))
595 +            System.err.print(info);
596 +    }
597 +
598 +    /**
599 +     * Checks that thread does not terminate within the default
600 +     * millisecond delay of {@code timeoutMillis()}.
601 +     */
602 +    void assertThreadStaysAlive(Thread thread) {
603 +        assertThreadStaysAlive(thread, timeoutMillis());
604 +    }
605 +
606 +    /**
607 +     * Checks that thread does not terminate within the given millisecond delay.
608 +     */
609 +    void assertThreadStaysAlive(Thread thread, long millis) {
610 +        try {
611 +            // No need to optimize the failing case via Thread.join.
612 +            delay(millis);
613 +            assertTrue(thread.isAlive());
614 +        } catch (InterruptedException ie) {
615 +            fail("Unexpected InterruptedException");
616 +        }
617 +    }
618 +
619 +    /**
620 +     * Checks that the threads do not terminate within the default
621 +     * millisecond delay of {@code timeoutMillis()}.
622 +     */
623 +    void assertThreadsStayAlive(Thread... threads) {
624 +        assertThreadsStayAlive(timeoutMillis(), threads);
625 +    }
626 +
627 +    /**
628 +     * Checks that the threads do not terminate within the given millisecond delay.
629 +     */
630 +    void assertThreadsStayAlive(long millis, Thread... threads) {
631 +        try {
632 +            // No need to optimize the failing case via Thread.join.
633 +            delay(millis);
634 +            for (Thread thread : threads)
635 +                assertTrue(thread.isAlive());
636 +        } catch (InterruptedException ie) {
637 +            fail("Unexpected InterruptedException");
638 +        }
639 +    }
640 +
641 +    /**
642 +     * Checks that future.get times out, with the default timeout of
643 +     * {@code timeoutMillis()}.
644 +     */
645 +    void assertFutureTimesOut(Future future) {
646 +        assertFutureTimesOut(future, timeoutMillis());
647 +    }
648 +
649 +    /**
650 +     * Checks that future.get times out, with the given millisecond timeout.
651 +     */
652 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
653 +        long startTime = System.nanoTime();
654 +        try {
655 +            future.get(timeoutMillis, MILLISECONDS);
656 +            shouldThrow();
657 +        } catch (TimeoutException success) {
658 +        } catch (Exception e) {
659 +            threadUnexpectedException(e);
660 +        } finally { future.cancel(true); }
661 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
662 +    }
663  
664      /**
665       * Fails with message "should throw exception".
# Line 507 | Line 712 | public class JSR166TestCase extends Test
712          SecurityManager sm = System.getSecurityManager();
713          if (sm == null) {
714              r.run();
715 +        }
716 +        runWithSecurityManagerWithPermissions(r, permissions);
717 +    }
718 +
719 +    /**
720 +     * Runs Runnable r with a security policy that permits precisely
721 +     * the specified permissions.  If there is no current security
722 +     * manager, a temporary one is set for the duration of the
723 +     * Runnable.  We require that any security manager permit
724 +     * getPolicy/setPolicy.
725 +     */
726 +    public void runWithSecurityManagerWithPermissions(Runnable r,
727 +                                                      Permission... permissions) {
728 +        SecurityManager sm = System.getSecurityManager();
729 +        if (sm == null) {
730              Policy savedPolicy = Policy.getPolicy();
731              try {
732                  Policy.setPolicy(permissivePolicy());
733                  System.setSecurityManager(new SecurityManager());
734 <                runWithPermissions(r, permissions);
734 >                runWithSecurityManagerWithPermissions(r, permissions);
735              } finally {
736                  System.setSecurityManager(null);
737                  Policy.setPolicy(savedPolicy);
# Line 559 | Line 779 | public class JSR166TestCase extends Test
779              return perms.implies(p);
780          }
781          public void refresh() {}
782 +        public String toString() {
783 +            List<Permission> ps = new ArrayList<Permission>();
784 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
785 +                ps.add(e.nextElement());
786 +            return "AdjustablePolicy with permissions " + ps;
787 +        }
788      }
789  
790      /**
# Line 586 | Line 812 | public class JSR166TestCase extends Test
812       */
813      void sleep(long millis) {
814          try {
815 <            Thread.sleep(millis);
815 >            delay(millis);
816          } catch (InterruptedException ie) {
817              AssertionFailedError afe =
818                  new AssertionFailedError("Unexpected InterruptedException");
# Line 596 | Line 822 | public class JSR166TestCase extends Test
822      }
823  
824      /**
825 <     * Sleeps until the timeout has elapsed, or interrupted.
600 <     * Does <em>NOT</em> throw InterruptedException.
601 <     */
602 <    void sleepTillInterrupted(long timeoutMillis) {
603 <        try {
604 <            Thread.sleep(timeoutMillis);
605 <        } catch (InterruptedException wakeup) {}
606 <    }
607 <
608 <    /**
609 <     * Waits up to the specified number of milliseconds for the given
825 >     * Spin-waits up to the specified number of milliseconds for the given
826       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
827       */
828      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
829 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
614 <        long t0 = System.nanoTime();
829 >        long startTime = System.nanoTime();
830          for (;;) {
831              Thread.State s = thread.getState();
832              if (s == Thread.State.BLOCKED ||
# Line 620 | Line 835 | public class JSR166TestCase extends Test
835                  return;
836              else if (s == Thread.State.TERMINATED)
837                  fail("Unexpected thread termination");
838 <            else if (System.nanoTime() - t0 > timeoutNanos) {
838 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
839                  threadAssertTrue(thread.isAlive());
840                  return;
841              }
# Line 629 | Line 844 | public class JSR166TestCase extends Test
844      }
845  
846      /**
847 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
848 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
849 +     */
850 +    void waitForThreadToEnterWaitState(Thread thread) {
851 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
852 +    }
853 +
854 +    /**
855       * Returns the number of milliseconds since time given by
856       * startNanoTime, which must have been previously returned from a
857       * call to {@link System.nanoTime()}.
# Line 658 | Line 881 | public class JSR166TestCase extends Test
881          } catch (InterruptedException ie) {
882              threadUnexpectedException(ie);
883          } finally {
884 <            if (t.isAlive()) {
884 >            if (t.getState() != Thread.State.TERMINATED) {
885                  t.interrupt();
886                  fail("Test timed out");
887              }
888          }
889      }
890  
891 +    /**
892 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
893 +     * terminate (using {@link Thread#join(long)}), else interrupts
894 +     * the thread (in the hope that it may terminate later) and fails.
895 +     */
896 +    void awaitTermination(Thread t) {
897 +        awaitTermination(t, LONG_DELAY_MS);
898 +    }
899 +
900      // Some convenient Runnable classes
901  
902      public abstract class CheckedRunnable implements Runnable {
# Line 727 | Line 959 | public class JSR166TestCase extends Test
959                  realRun();
960                  threadShouldThrow("InterruptedException");
961              } catch (InterruptedException success) {
962 +                threadAssertFalse(Thread.interrupted());
963              } catch (Throwable t) {
964                  threadUnexpectedException(t);
965              }
# Line 756 | Line 989 | public class JSR166TestCase extends Test
989                  threadShouldThrow("InterruptedException");
990                  return result;
991              } catch (InterruptedException success) {
992 +                threadAssertFalse(Thread.interrupted());
993              } catch (Throwable t) {
994                  threadUnexpectedException(t);
995              }
# Line 787 | Line 1021 | public class JSR166TestCase extends Test
1021              }};
1022      }
1023  
1024 +    public Runnable awaiter(final CountDownLatch latch) {
1025 +        return new CheckedRunnable() {
1026 +            public void realRun() throws InterruptedException {
1027 +                await(latch);
1028 +            }};
1029 +    }
1030 +
1031 +    public void await(CountDownLatch latch) {
1032 +        try {
1033 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1034 +        } catch (Throwable t) {
1035 +            threadUnexpectedException(t);
1036 +        }
1037 +    }
1038 +
1039 +    public void await(Semaphore semaphore) {
1040 +        try {
1041 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1042 +        } catch (Throwable t) {
1043 +            threadUnexpectedException(t);
1044 +        }
1045 +    }
1046 +
1047 + //     /**
1048 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1049 + //      */
1050 + //     public void await(AtomicBoolean flag) {
1051 + //         await(flag, LONG_DELAY_MS);
1052 + //     }
1053 +
1054 + //     /**
1055 + //      * Spin-waits up to the specified timeout until flag becomes true.
1056 + //      */
1057 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1058 + //         long startTime = System.nanoTime();
1059 + //         while (!flag.get()) {
1060 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1061 + //                 throw new AssertionFailedError("timed out");
1062 + //             Thread.yield();
1063 + //         }
1064 + //     }
1065 +
1066      public static class NPETask implements Callable<String> {
1067          public String call() { throw new NullPointerException(); }
1068      }
# Line 797 | Line 1073 | public class JSR166TestCase extends Test
1073  
1074      public class ShortRunnable extends CheckedRunnable {
1075          protected void realRun() throws Throwable {
1076 <            Thread.sleep(SHORT_DELAY_MS);
1076 >            delay(SHORT_DELAY_MS);
1077          }
1078      }
1079  
1080      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1081          protected void realRun() throws InterruptedException {
1082 <            Thread.sleep(SHORT_DELAY_MS);
1082 >            delay(SHORT_DELAY_MS);
1083          }
1084      }
1085  
1086      public class SmallRunnable extends CheckedRunnable {
1087          protected void realRun() throws Throwable {
1088 <            Thread.sleep(SMALL_DELAY_MS);
1088 >            delay(SMALL_DELAY_MS);
1089          }
1090      }
1091  
1092      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1093          protected void realRun() {
1094              try {
1095 <                Thread.sleep(SMALL_DELAY_MS);
1095 >                delay(SMALL_DELAY_MS);
1096              } catch (InterruptedException ok) {}
1097          }
1098      }
1099  
1100      public class SmallCallable extends CheckedCallable {
1101          protected Object realCall() throws InterruptedException {
1102 <            Thread.sleep(SMALL_DELAY_MS);
1102 >            delay(SMALL_DELAY_MS);
1103              return Boolean.TRUE;
1104          }
1105      }
1106  
1107      public class MediumRunnable extends CheckedRunnable {
1108          protected void realRun() throws Throwable {
1109 <            Thread.sleep(MEDIUM_DELAY_MS);
1109 >            delay(MEDIUM_DELAY_MS);
1110          }
1111      }
1112  
1113      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1114          protected void realRun() throws InterruptedException {
1115 <            Thread.sleep(MEDIUM_DELAY_MS);
1115 >            delay(MEDIUM_DELAY_MS);
1116          }
1117      }
1118  
# Line 844 | Line 1120 | public class JSR166TestCase extends Test
1120          return new CheckedRunnable() {
1121              protected void realRun() {
1122                  try {
1123 <                    Thread.sleep(timeoutMillis);
1123 >                    delay(timeoutMillis);
1124                  } catch (InterruptedException ok) {}
1125              }};
1126      }
# Line 852 | Line 1128 | public class JSR166TestCase extends Test
1128      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1129          protected void realRun() {
1130              try {
1131 <                Thread.sleep(MEDIUM_DELAY_MS);
1131 >                delay(MEDIUM_DELAY_MS);
1132              } catch (InterruptedException ok) {}
1133          }
1134      }
# Line 860 | Line 1136 | public class JSR166TestCase extends Test
1136      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1137          protected void realRun() {
1138              try {
1139 <                Thread.sleep(LONG_DELAY_MS);
1139 >                delay(LONG_DELAY_MS);
1140              } catch (InterruptedException ok) {}
1141          }
1142      }
# Line 884 | Line 1160 | public class JSR166TestCase extends Test
1160                  public boolean isDone() { return done; }
1161                  public void run() {
1162                      try {
1163 <                        Thread.sleep(timeoutMillis);
1163 >                        delay(timeoutMillis);
1164                          done = true;
1165                      } catch (InterruptedException ok) {}
1166                  }
# Line 895 | Line 1171 | public class JSR166TestCase extends Test
1171          public volatile boolean done = false;
1172          public void run() {
1173              try {
1174 <                Thread.sleep(SHORT_DELAY_MS);
1174 >                delay(SHORT_DELAY_MS);
1175                  done = true;
1176              } catch (InterruptedException ok) {}
1177          }
# Line 905 | Line 1181 | public class JSR166TestCase extends Test
1181          public volatile boolean done = false;
1182          public void run() {
1183              try {
1184 <                Thread.sleep(SMALL_DELAY_MS);
1184 >                delay(SMALL_DELAY_MS);
1185                  done = true;
1186              } catch (InterruptedException ok) {}
1187          }
# Line 915 | Line 1191 | public class JSR166TestCase extends Test
1191          public volatile boolean done = false;
1192          public void run() {
1193              try {
1194 <                Thread.sleep(MEDIUM_DELAY_MS);
1194 >                delay(MEDIUM_DELAY_MS);
1195                  done = true;
1196              } catch (InterruptedException ok) {}
1197          }
# Line 925 | Line 1201 | public class JSR166TestCase extends Test
1201          public volatile boolean done = false;
1202          public void run() {
1203              try {
1204 <                Thread.sleep(LONG_DELAY_MS);
1204 >                delay(LONG_DELAY_MS);
1205                  done = true;
1206              } catch (InterruptedException ok) {}
1207          }
# Line 942 | Line 1218 | public class JSR166TestCase extends Test
1218          public volatile boolean done = false;
1219          public Object call() {
1220              try {
1221 <                Thread.sleep(SMALL_DELAY_MS);
1221 >                delay(SMALL_DELAY_MS);
1222                  done = true;
1223              } catch (InterruptedException ok) {}
1224              return Boolean.TRUE;
# Line 989 | Line 1265 | public class JSR166TestCase extends Test
1265      }
1266  
1267      /**
1268 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1269 <     * of throwing checked exceptions.
1268 >     * A CyclicBarrier that uses timed await and fails with
1269 >     * AssertionFailedErrors instead of throwing checked exceptions.
1270       */
1271      public class CheckedBarrier extends CyclicBarrier {
1272          public CheckedBarrier(int parties) { super(parties); }
1273  
1274          public int await() {
1275              try {
1276 <                return super.await();
1276 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1277 >            } catch (TimeoutException e) {
1278 >                throw new AssertionFailedError("timed out");
1279              } catch (Exception e) {
1280                  AssertionFailedError afe =
1281                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1007 | Line 1285 | public class JSR166TestCase extends Test
1285          }
1286      }
1287  
1288 +    void checkEmpty(BlockingQueue q) {
1289 +        try {
1290 +            assertTrue(q.isEmpty());
1291 +            assertEquals(0, q.size());
1292 +            assertNull(q.peek());
1293 +            assertNull(q.poll());
1294 +            assertNull(q.poll(0, MILLISECONDS));
1295 +            assertEquals(q.toString(), "[]");
1296 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1297 +            assertFalse(q.iterator().hasNext());
1298 +            try {
1299 +                q.element();
1300 +                shouldThrow();
1301 +            } catch (NoSuchElementException success) {}
1302 +            try {
1303 +                q.iterator().next();
1304 +                shouldThrow();
1305 +            } catch (NoSuchElementException success) {}
1306 +            try {
1307 +                q.remove();
1308 +                shouldThrow();
1309 +            } catch (NoSuchElementException success) {}
1310 +        } catch (InterruptedException ie) {
1311 +            threadUnexpectedException(ie);
1312 +        }
1313 +    }
1314 +
1315 +    void assertSerialEquals(Object x, Object y) {
1316 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1317 +    }
1318 +
1319 +    void assertNotSerialEquals(Object x, Object y) {
1320 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1321 +    }
1322 +
1323 +    byte[] serialBytes(Object o) {
1324 +        try {
1325 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1326 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1327 +            oos.writeObject(o);
1328 +            oos.flush();
1329 +            oos.close();
1330 +            return bos.toByteArray();
1331 +        } catch (Throwable t) {
1332 +            threadUnexpectedException(t);
1333 +            return new byte[0];
1334 +        }
1335 +    }
1336 +
1337 +    @SuppressWarnings("unchecked")
1338 +    <T> T serialClone(T o) {
1339 +        try {
1340 +            ObjectInputStream ois = new ObjectInputStream
1341 +                (new ByteArrayInputStream(serialBytes(o)));
1342 +            T clone = (T) ois.readObject();
1343 +            assertSame(o.getClass(), clone.getClass());
1344 +            return clone;
1345 +        } catch (Throwable t) {
1346 +            threadUnexpectedException(t);
1347 +            return null;
1348 +        }
1349 +    }
1350   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines