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.60 by jsr166, Wed Oct 6 07:49:22 2010 UTC vs.
Revision 1.80 by jsr166, Fri May 13 21:48:58 2011 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.util.Arrays;
15 + import java.util.NoSuchElementException;
16   import java.util.PropertyPermission;
17   import java.util.concurrent.*;
18   import java.util.concurrent.atomic.AtomicReference;
19   import static java.util.concurrent.TimeUnit.MILLISECONDS;
20 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 96 | Line 103 | public class JSR166TestCase extends Test
103      private static final boolean useSecurityManager =
104          Boolean.getBoolean("jsr166.useSecurityManager");
105  
106 +    protected static final boolean expensiveTests =
107 +        Boolean.getBoolean("jsr166.expensiveTests");
108 +
109 +    /**
110 +     * If true, report on stdout all "slow" tests, that is, ones that
111 +     * take more than profileThreshold milliseconds to execute.
112 +     */
113 +    private static final boolean profileTests =
114 +        Boolean.getBoolean("jsr166.profileTests");
115 +
116 +    /**
117 +     * The number of milliseconds that tests are permitted for
118 +     * execution without being reported, when profileTests is set.
119 +     */
120 +    private static final long profileThreshold =
121 +        Long.getLong("jsr166.profileThreshold", 100);
122 +
123 +    protected void runTest() throws Throwable {
124 +        if (profileTests)
125 +            runTestProfiled();
126 +        else
127 +            super.runTest();
128 +    }
129 +
130 +    protected void runTestProfiled() throws Throwable {
131 +        long t0 = System.nanoTime();
132 +        try {
133 +            super.runTest();
134 +        } finally {
135 +            long elapsedMillis =
136 +                (System.nanoTime() - t0) / (1000L * 1000L);
137 +            if (elapsedMillis >= profileThreshold)
138 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
139 +        }
140 +    }
141 +
142      /**
143       * Runs all JSR166 unit tests using junit.textui.TestRunner
144       */
# Line 223 | Line 266 | public class JSR166TestCase extends Test
266          SHORT_DELAY_MS = getShortDelay();
267          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
268          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
269 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
269 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
270      }
271  
272      /**
# Line 252 | Line 295 | public class JSR166TestCase extends Test
295       * earlier by threadRecordFailure.
296       */
297      public void tearDown() throws Exception {
298 <        Throwable t = threadFailure.get();
298 >        Throwable t = threadFailure.getAndSet(null);
299          if (t != null) {
300              if (t instanceof Error)
301                  throw (Error) t;
# Line 404 | Line 447 | public class JSR166TestCase extends Test
447      }
448  
449      /**
450 +     * Delays, via Thread.sleep for the given millisecond delay, but
451 +     * if the sleep is shorter than specified, may re-sleep or yield
452 +     * until time elapses.
453 +     */
454 +    public static void delay(long millis) throws InterruptedException {
455 +        long startTime = System.nanoTime();
456 +        long ns = millis * 1000 * 1000;
457 +        for (;;) {
458 +            if (millis > 0L)
459 +                Thread.sleep(millis);
460 +            else // too short to sleep
461 +                Thread.yield();
462 +            long d = ns - (System.nanoTime() - startTime);
463 +            if (d > 0L)
464 +                millis = d / (1000 * 1000);
465 +            else
466 +                break;
467 +        }
468 +    }
469 +
470 +    /**
471       * Waits out termination of a thread pool or fails doing so.
472       */
473      public void joinPool(ExecutorService exec) {
474          try {
475              exec.shutdown();
476              assertTrue("ExecutorService did not terminate in a timely manner",
477 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
477 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
478          } catch (SecurityException ok) {
479              // Allowed in case test doesn't have privs
480          } catch (InterruptedException ie) {
# Line 418 | Line 482 | public class JSR166TestCase extends Test
482          }
483      }
484  
485 +    /**
486 +     * Checks that thread does not terminate within the given millisecond delay.
487 +     */
488 +    public void assertThreadStaysAlive(Thread thread, long millis) {
489 +        try {
490 +            // No need to optimize the failing case via Thread.join.
491 +            delay(millis);
492 +            assertTrue(thread.isAlive());
493 +        } catch (InterruptedException ie) {
494 +            fail("Unexpected InterruptedException");
495 +        }
496 +    }
497  
498      /**
499       * Fails with message "should throw exception".
# Line 549 | Line 625 | public class JSR166TestCase extends Test
625       */
626      void sleep(long millis) {
627          try {
628 <            Thread.sleep(millis);
628 >            delay(millis);
629          } catch (InterruptedException ie) {
630              AssertionFailedError afe =
631                  new AssertionFailedError("Unexpected InterruptedException");
# Line 569 | Line 645 | public class JSR166TestCase extends Test
645      }
646  
647      /**
648 +     * Waits up to the specified number of milliseconds for the given
649 +     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
650 +     */
651 +    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
652 +        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 +        long t0 = System.nanoTime();
654 +        for (;;) {
655 +            Thread.State s = thread.getState();
656 +            if (s == Thread.State.BLOCKED ||
657 +                s == Thread.State.WAITING ||
658 +                s == Thread.State.TIMED_WAITING)
659 +                return;
660 +            else if (s == Thread.State.TERMINATED)
661 +                fail("Unexpected thread termination");
662 +            else if (System.nanoTime() - t0 > timeoutNanos) {
663 +                threadAssertTrue(thread.isAlive());
664 +                return;
665 +            }
666 +            Thread.yield();
667 +        }
668 +    }
669 +
670 +    /**
671 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
672 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
673 +     */
674 +    void waitForThreadToEnterWaitState(Thread thread) {
675 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
676 +    }
677 +
678 +    /**
679 +     * Returns the number of milliseconds since time given by
680 +     * startNanoTime, which must have been previously returned from a
681 +     * call to {@link System.nanoTime()}.
682 +     */
683 +    long millisElapsedSince(long startNanoTime) {
684 +        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
685 +    }
686 +
687 +    /**
688       * Returns a new started daemon Thread running the given runnable.
689       */
690      Thread newStartedThread(Runnable runnable) {
# Line 596 | Line 712 | public class JSR166TestCase extends Test
712          }
713      }
714  
715 +    /**
716 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
717 +     * terminate (using {@link Thread#join(long)}), else interrupts
718 +     * the thread (in the hope that it may terminate later) and fails.
719 +     */
720 +    void awaitTermination(Thread t) {
721 +        awaitTermination(t, LONG_DELAY_MS);
722 +    }
723 +
724      // Some convenient Runnable classes
725  
726      public abstract class CheckedRunnable implements Runnable {
# Line 710 | Line 835 | public class JSR166TestCase extends Test
835  
836      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
837          return new CheckedCallable<String>() {
838 <            public String realCall() {
838 >            protected String realCall() {
839                  try {
840                      latch.await();
841                  } catch (InterruptedException quittingTime) {}
# Line 718 | Line 843 | public class JSR166TestCase extends Test
843              }};
844      }
845  
846 +    public Runnable awaiter(final CountDownLatch latch) {
847 +        return new CheckedRunnable() {
848 +            public void realRun() throws InterruptedException {
849 +                await(latch);
850 +            }};
851 +    }
852 +
853 +    public void await(CountDownLatch latch) {
854 +        try {
855 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
856 +        } catch (Throwable t) {
857 +            threadUnexpectedException(t);
858 +        }
859 +    }
860 +
861      public static class NPETask implements Callable<String> {
862          public String call() { throw new NullPointerException(); }
863      }
# Line 728 | Line 868 | public class JSR166TestCase extends Test
868  
869      public class ShortRunnable extends CheckedRunnable {
870          protected void realRun() throws Throwable {
871 <            Thread.sleep(SHORT_DELAY_MS);
871 >            delay(SHORT_DELAY_MS);
872          }
873      }
874  
875      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
876          protected void realRun() throws InterruptedException {
877 <            Thread.sleep(SHORT_DELAY_MS);
877 >            delay(SHORT_DELAY_MS);
878          }
879      }
880  
881      public class SmallRunnable extends CheckedRunnable {
882          protected void realRun() throws Throwable {
883 <            Thread.sleep(SMALL_DELAY_MS);
883 >            delay(SMALL_DELAY_MS);
884          }
885      }
886  
887      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
888          protected void realRun() {
889              try {
890 <                Thread.sleep(SMALL_DELAY_MS);
890 >                delay(SMALL_DELAY_MS);
891              } catch (InterruptedException ok) {}
892          }
893      }
894  
895      public class SmallCallable extends CheckedCallable {
896          protected Object realCall() throws InterruptedException {
897 <            Thread.sleep(SMALL_DELAY_MS);
897 >            delay(SMALL_DELAY_MS);
898              return Boolean.TRUE;
899          }
900      }
901  
902      public class MediumRunnable extends CheckedRunnable {
903          protected void realRun() throws Throwable {
904 <            Thread.sleep(MEDIUM_DELAY_MS);
904 >            delay(MEDIUM_DELAY_MS);
905          }
906      }
907  
908      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
909          protected void realRun() throws InterruptedException {
910 <            Thread.sleep(MEDIUM_DELAY_MS);
910 >            delay(MEDIUM_DELAY_MS);
911          }
912      }
913  
914 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
915 +        return new CheckedRunnable() {
916 +            protected void realRun() {
917 +                try {
918 +                    delay(timeoutMillis);
919 +                } catch (InterruptedException ok) {}
920 +            }};
921 +    }
922 +
923      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
924          protected void realRun() {
925              try {
926 <                Thread.sleep(MEDIUM_DELAY_MS);
926 >                delay(MEDIUM_DELAY_MS);
927              } catch (InterruptedException ok) {}
928          }
929      }
# Line 782 | Line 931 | public class JSR166TestCase extends Test
931      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
932          protected void realRun() {
933              try {
934 <                Thread.sleep(LONG_DELAY_MS);
934 >                delay(LONG_DELAY_MS);
935              } catch (InterruptedException ok) {}
936          }
937      }
# Line 796 | Line 945 | public class JSR166TestCase extends Test
945          }
946      }
947  
948 +    public interface TrackedRunnable extends Runnable {
949 +        boolean isDone();
950 +    }
951 +
952 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
953 +        return new TrackedRunnable() {
954 +                private volatile boolean done = false;
955 +                public boolean isDone() { return done; }
956 +                public void run() {
957 +                    try {
958 +                        delay(timeoutMillis);
959 +                        done = true;
960 +                    } catch (InterruptedException ok) {}
961 +                }
962 +            };
963 +    }
964 +
965      public static class TrackedShortRunnable implements Runnable {
966          public volatile boolean done = false;
967          public void run() {
968              try {
969 <                Thread.sleep(SMALL_DELAY_MS);
969 >                delay(SHORT_DELAY_MS);
970 >                done = true;
971 >            } catch (InterruptedException ok) {}
972 >        }
973 >    }
974 >
975 >    public static class TrackedSmallRunnable implements Runnable {
976 >        public volatile boolean done = false;
977 >        public void run() {
978 >            try {
979 >                delay(SMALL_DELAY_MS);
980                  done = true;
981              } catch (InterruptedException ok) {}
982          }
# Line 810 | Line 986 | public class JSR166TestCase extends Test
986          public volatile boolean done = false;
987          public void run() {
988              try {
989 <                Thread.sleep(MEDIUM_DELAY_MS);
989 >                delay(MEDIUM_DELAY_MS);
990                  done = true;
991              } catch (InterruptedException ok) {}
992          }
# Line 820 | Line 996 | public class JSR166TestCase extends Test
996          public volatile boolean done = false;
997          public void run() {
998              try {
999 <                Thread.sleep(LONG_DELAY_MS);
999 >                delay(LONG_DELAY_MS);
1000                  done = true;
1001              } catch (InterruptedException ok) {}
1002          }
# Line 837 | Line 1013 | public class JSR166TestCase extends Test
1013          public volatile boolean done = false;
1014          public Object call() {
1015              try {
1016 <                Thread.sleep(SMALL_DELAY_MS);
1016 >                delay(SMALL_DELAY_MS);
1017                  done = true;
1018              } catch (InterruptedException ok) {}
1019              return Boolean.TRUE;
# Line 902 | Line 1078 | public class JSR166TestCase extends Test
1078          }
1079      }
1080  
1081 +    public void checkEmpty(BlockingQueue q) {
1082 +        try {
1083 +            assertTrue(q.isEmpty());
1084 +            assertEquals(0, q.size());
1085 +            assertNull(q.peek());
1086 +            assertNull(q.poll());
1087 +            assertNull(q.poll(0, MILLISECONDS));
1088 +            assertEquals(q.toString(), "[]");
1089 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1090 +            assertFalse(q.iterator().hasNext());
1091 +            try {
1092 +                q.element();
1093 +                shouldThrow();
1094 +            } catch (NoSuchElementException success) {}
1095 +            try {
1096 +                q.iterator().next();
1097 +                shouldThrow();
1098 +            } catch (NoSuchElementException success) {}
1099 +            try {
1100 +                q.remove();
1101 +                shouldThrow();
1102 +            } catch (NoSuchElementException success) {}
1103 +        } catch (InterruptedException ie) {
1104 +            threadUnexpectedException(ie);
1105 +        }
1106 +    }
1107 +
1108 +    @SuppressWarnings("unchecked")
1109 +    public <T> T serialClone(T o) {
1110 +        try {
1111 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1112 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1113 +            oos.writeObject(o);
1114 +            oos.flush();
1115 +            oos.close();
1116 +            ByteArrayInputStream bin =
1117 +                new ByteArrayInputStream(bos.toByteArray());
1118 +            ObjectInputStream ois = new ObjectInputStream(bin);
1119 +            return (T) ois.readObject();
1120 +        } catch (Throwable t) {
1121 +            threadUnexpectedException(t);
1122 +            return null;
1123 +        }
1124 +    }
1125   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines