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.63 by jsr166, Mon Oct 11 08:30:01 2010 UTC vs.
Revision 1.88 by jsr166, Tue May 31 15:01:24 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.Date;
16 + import java.util.NoSuchElementException;
17   import java.util.PropertyPermission;
18   import java.util.concurrent.*;
19 + import java.util.concurrent.atomic.AtomicBoolean;
20   import java.util.concurrent.atomic.AtomicReference;
21   import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
23   import java.security.CodeSource;
24   import java.security.Permission;
25   import java.security.PermissionCollection;
# Line 251 | Line 260 | public class JSR166TestCase extends Test
260          return 50;
261      }
262  
254
263      /**
264       * Sets delays as multiples of SHORT_DELAY.
265       */
# Line 259 | Line 267 | public class JSR166TestCase extends Test
267          SHORT_DELAY_MS = getShortDelay();
268          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
269          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
270 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
270 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
271 >    }
272 >
273 >    /**
274 >     * Returns a timeout in milliseconds to be used in tests that
275 >     * verify that operations block or time out.
276 >     */
277 >    long timeoutMillis() {
278 >        return SHORT_DELAY_MS / 4;
279 >    }
280 >
281 >    /**
282 >     * Returns a new Date instance representing a time delayMillis
283 >     * milliseconds in the future.
284 >     */
285 >    Date delayedDate(long delayMillis) {
286 >        return new Date(System.currentTimeMillis() + delayMillis);
287      }
288  
289      /**
# Line 283 | Line 307 | public class JSR166TestCase extends Test
307      }
308  
309      /**
310 +     * Extra checks that get done for all test cases.
311 +     *
312       * Triggers test case failure if any thread assertions have failed,
313       * by rethrowing, in the test harness thread, any exception recorded
314       * earlier by threadRecordFailure.
315 +     *
316 +     * Triggers test case failure if interrupt status is set in the main thread.
317       */
318      public void tearDown() throws Exception {
319 <        Throwable t = threadFailure.get();
319 >        Throwable t = threadFailure.getAndSet(null);
320          if (t != null) {
321              if (t instanceof Error)
322                  throw (Error) t;
# Line 303 | Line 331 | public class JSR166TestCase extends Test
331                  throw afe;
332              }
333          }
334 +
335 +        if (Thread.interrupted())
336 +            throw new AssertionFailedError("interrupt status set in main thread");
337      }
338  
339      /**
# Line 434 | Line 465 | public class JSR166TestCase extends Test
465          else {
466              AssertionFailedError afe =
467                  new AssertionFailedError("unexpected exception: " + t);
468 <            t.initCause(t);
468 >            afe.initCause(t);
469              throw afe;
470          }
471      }
472  
473      /**
474 +     * Delays, via Thread.sleep, for the given millisecond delay, but
475 +     * if the sleep is shorter than specified, may re-sleep or yield
476 +     * until time elapses.
477 +     */
478 +    static void delay(long millis) throws InterruptedException {
479 +        long startTime = System.nanoTime();
480 +        long ns = millis * 1000 * 1000;
481 +        for (;;) {
482 +            if (millis > 0L)
483 +                Thread.sleep(millis);
484 +            else // too short to sleep
485 +                Thread.yield();
486 +            long d = ns - (System.nanoTime() - startTime);
487 +            if (d > 0L)
488 +                millis = d / (1000 * 1000);
489 +            else
490 +                break;
491 +        }
492 +    }
493 +
494 +    /**
495       * Waits out termination of a thread pool or fails doing so.
496       */
497 <    public void joinPool(ExecutorService exec) {
497 >    void joinPool(ExecutorService exec) {
498          try {
499              exec.shutdown();
500              assertTrue("ExecutorService did not terminate in a timely manner",
501 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
501 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
502          } catch (SecurityException ok) {
503              // Allowed in case test doesn't have privs
504          } catch (InterruptedException ie) {
# Line 454 | Line 506 | public class JSR166TestCase extends Test
506          }
507      }
508  
509 +    /**
510 +     * Checks that thread does not terminate within the default
511 +     * millisecond delay of {@code timeoutMillis()}.
512 +     */
513 +    void assertThreadStaysAlive(Thread thread) {
514 +        assertThreadStaysAlive(thread, timeoutMillis());
515 +    }
516 +
517 +    /**
518 +     * Checks that thread does not terminate within the given millisecond delay.
519 +     */
520 +    void assertThreadStaysAlive(Thread thread, long millis) {
521 +        try {
522 +            // No need to optimize the failing case via Thread.join.
523 +            delay(millis);
524 +            assertTrue(thread.isAlive());
525 +        } catch (InterruptedException ie) {
526 +            fail("Unexpected InterruptedException");
527 +        }
528 +    }
529 +
530 +    /**
531 +     * Checks that future.get times out, with the default timeout of
532 +     * {@code timeoutMillis()}.
533 +     */
534 +    void assertFutureTimesOut(Future future) {
535 +        assertFutureTimesOut(future, timeoutMillis());
536 +    }
537 +
538 +    /**
539 +     * Checks that future.get times out, with the given millisecond timeout.
540 +     */
541 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
542 +        long startTime = System.nanoTime();
543 +        try {
544 +            future.get(timeoutMillis, MILLISECONDS);
545 +            shouldThrow();
546 +        } catch (TimeoutException success) {
547 +        } catch (Exception e) {
548 +            threadUnexpectedException(e);
549 +        } finally { future.cancel(true); }
550 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
551 +    }
552  
553      /**
554       * Fails with message "should throw exception".
# Line 585 | Line 680 | public class JSR166TestCase extends Test
680       */
681      void sleep(long millis) {
682          try {
683 <            Thread.sleep(millis);
683 >            delay(millis);
684          } catch (InterruptedException ie) {
685              AssertionFailedError afe =
686                  new AssertionFailedError("Unexpected InterruptedException");
# Line 595 | Line 690 | public class JSR166TestCase extends Test
690      }
691  
692      /**
693 <     * Sleeps until the timeout has elapsed, or interrupted.
694 <     * Does <em>NOT</em> throw InterruptedException.
693 >     * Spin-waits up to the specified number of milliseconds for the given
694 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
695       */
696 <    void sleepTillInterrupted(long timeoutMillis) {
697 <        try {
698 <            Thread.sleep(timeoutMillis);
699 <        } catch (InterruptedException wakeup) {}
696 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
697 >        long startTime = System.nanoTime();
698 >        for (;;) {
699 >            Thread.State s = thread.getState();
700 >            if (s == Thread.State.BLOCKED ||
701 >                s == Thread.State.WAITING ||
702 >                s == Thread.State.TIMED_WAITING)
703 >                return;
704 >            else if (s == Thread.State.TERMINATED)
705 >                fail("Unexpected thread termination");
706 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
707 >                threadAssertTrue(thread.isAlive());
708 >                return;
709 >            }
710 >            Thread.yield();
711 >        }
712 >    }
713 >
714 >    /**
715 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
716 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
717 >     */
718 >    void waitForThreadToEnterWaitState(Thread thread) {
719 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
720 >    }
721 >
722 >    /**
723 >     * Returns the number of milliseconds since time given by
724 >     * startNanoTime, which must have been previously returned from a
725 >     * call to {@link System.nanoTime()}.
726 >     */
727 >    long millisElapsedSince(long startNanoTime) {
728 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
729      }
730  
731      /**
# Line 625 | Line 749 | public class JSR166TestCase extends Test
749          } catch (InterruptedException ie) {
750              threadUnexpectedException(ie);
751          } finally {
752 <            if (t.isAlive()) {
752 >            if (t.getState() != Thread.State.TERMINATED) {
753                  t.interrupt();
754                  fail("Test timed out");
755              }
756          }
757      }
758  
759 +    /**
760 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
761 +     * terminate (using {@link Thread#join(long)}), else interrupts
762 +     * the thread (in the hope that it may terminate later) and fails.
763 +     */
764 +    void awaitTermination(Thread t) {
765 +        awaitTermination(t, LONG_DELAY_MS);
766 +    }
767 +
768      // Some convenient Runnable classes
769  
770      public abstract class CheckedRunnable implements Runnable {
# Line 694 | Line 827 | public class JSR166TestCase extends Test
827                  realRun();
828                  threadShouldThrow("InterruptedException");
829              } catch (InterruptedException success) {
830 +                threadAssertFalse(Thread.interrupted());
831              } catch (Throwable t) {
832                  threadUnexpectedException(t);
833              }
# Line 723 | Line 857 | public class JSR166TestCase extends Test
857                  threadShouldThrow("InterruptedException");
858                  return result;
859              } catch (InterruptedException success) {
860 +                threadAssertFalse(Thread.interrupted());
861              } catch (Throwable t) {
862                  threadUnexpectedException(t);
863              }
# Line 746 | Line 881 | public class JSR166TestCase extends Test
881  
882      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
883          return new CheckedCallable<String>() {
884 <            public String realCall() {
884 >            protected String realCall() {
885                  try {
886                      latch.await();
887                  } catch (InterruptedException quittingTime) {}
# Line 754 | Line 889 | public class JSR166TestCase extends Test
889              }};
890      }
891  
892 +    public Runnable awaiter(final CountDownLatch latch) {
893 +        return new CheckedRunnable() {
894 +            public void realRun() throws InterruptedException {
895 +                await(latch);
896 +            }};
897 +    }
898 +
899 +    public void await(CountDownLatch latch) {
900 +        try {
901 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
902 +        } catch (Throwable t) {
903 +            threadUnexpectedException(t);
904 +        }
905 +    }
906 +
907 + //     /**
908 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
909 + //      */
910 + //     public void await(AtomicBoolean flag) {
911 + //         await(flag, LONG_DELAY_MS);
912 + //     }
913 +
914 + //     /**
915 + //      * Spin-waits up to the specified timeout until flag becomes true.
916 + //      */
917 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
918 + //         long startTime = System.nanoTime();
919 + //         while (!flag.get()) {
920 + //             if (millisElapsedSince(startTime) > timeoutMillis)
921 + //                 throw new AssertionFailedError("timed out");
922 + //             Thread.yield();
923 + //         }
924 + //     }
925 +
926      public static class NPETask implements Callable<String> {
927          public String call() { throw new NullPointerException(); }
928      }
# Line 764 | Line 933 | public class JSR166TestCase extends Test
933  
934      public class ShortRunnable extends CheckedRunnable {
935          protected void realRun() throws Throwable {
936 <            Thread.sleep(SHORT_DELAY_MS);
936 >            delay(SHORT_DELAY_MS);
937          }
938      }
939  
940      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
941          protected void realRun() throws InterruptedException {
942 <            Thread.sleep(SHORT_DELAY_MS);
942 >            delay(SHORT_DELAY_MS);
943          }
944      }
945  
946      public class SmallRunnable extends CheckedRunnable {
947          protected void realRun() throws Throwable {
948 <            Thread.sleep(SMALL_DELAY_MS);
948 >            delay(SMALL_DELAY_MS);
949          }
950      }
951  
952      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
953          protected void realRun() {
954              try {
955 <                Thread.sleep(SMALL_DELAY_MS);
955 >                delay(SMALL_DELAY_MS);
956              } catch (InterruptedException ok) {}
957          }
958      }
959  
960      public class SmallCallable extends CheckedCallable {
961          protected Object realCall() throws InterruptedException {
962 <            Thread.sleep(SMALL_DELAY_MS);
962 >            delay(SMALL_DELAY_MS);
963              return Boolean.TRUE;
964          }
965      }
966  
967      public class MediumRunnable extends CheckedRunnable {
968          protected void realRun() throws Throwable {
969 <            Thread.sleep(MEDIUM_DELAY_MS);
969 >            delay(MEDIUM_DELAY_MS);
970          }
971      }
972  
973      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
974          protected void realRun() throws InterruptedException {
975 <            Thread.sleep(MEDIUM_DELAY_MS);
975 >            delay(MEDIUM_DELAY_MS);
976          }
977      }
978  
# Line 811 | Line 980 | public class JSR166TestCase extends Test
980          return new CheckedRunnable() {
981              protected void realRun() {
982                  try {
983 <                    Thread.sleep(timeoutMillis);
983 >                    delay(timeoutMillis);
984                  } catch (InterruptedException ok) {}
985              }};
986      }
# Line 819 | Line 988 | public class JSR166TestCase extends Test
988      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
989          protected void realRun() {
990              try {
991 <                Thread.sleep(MEDIUM_DELAY_MS);
991 >                delay(MEDIUM_DELAY_MS);
992              } catch (InterruptedException ok) {}
993          }
994      }
# Line 827 | Line 996 | public class JSR166TestCase extends Test
996      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
997          protected void realRun() {
998              try {
999 <                Thread.sleep(LONG_DELAY_MS);
999 >                delay(LONG_DELAY_MS);
1000              } catch (InterruptedException ok) {}
1001          }
1002      }
# Line 851 | Line 1020 | public class JSR166TestCase extends Test
1020                  public boolean isDone() { return done; }
1021                  public void run() {
1022                      try {
1023 <                        Thread.sleep(timeoutMillis);
1023 >                        delay(timeoutMillis);
1024                          done = true;
1025                      } catch (InterruptedException ok) {}
1026                  }
# Line 862 | Line 1031 | public class JSR166TestCase extends Test
1031          public volatile boolean done = false;
1032          public void run() {
1033              try {
1034 <                Thread.sleep(SHORT_DELAY_MS);
1034 >                delay(SHORT_DELAY_MS);
1035                  done = true;
1036              } catch (InterruptedException ok) {}
1037          }
# Line 872 | Line 1041 | public class JSR166TestCase extends Test
1041          public volatile boolean done = false;
1042          public void run() {
1043              try {
1044 <                Thread.sleep(SMALL_DELAY_MS);
1044 >                delay(SMALL_DELAY_MS);
1045                  done = true;
1046              } catch (InterruptedException ok) {}
1047          }
# Line 882 | Line 1051 | public class JSR166TestCase extends Test
1051          public volatile boolean done = false;
1052          public void run() {
1053              try {
1054 <                Thread.sleep(MEDIUM_DELAY_MS);
1054 >                delay(MEDIUM_DELAY_MS);
1055                  done = true;
1056              } catch (InterruptedException ok) {}
1057          }
# Line 892 | Line 1061 | public class JSR166TestCase extends Test
1061          public volatile boolean done = false;
1062          public void run() {
1063              try {
1064 <                Thread.sleep(LONG_DELAY_MS);
1064 >                delay(LONG_DELAY_MS);
1065                  done = true;
1066              } catch (InterruptedException ok) {}
1067          }
# Line 909 | Line 1078 | public class JSR166TestCase extends Test
1078          public volatile boolean done = false;
1079          public Object call() {
1080              try {
1081 <                Thread.sleep(SMALL_DELAY_MS);
1081 >                delay(SMALL_DELAY_MS);
1082                  done = true;
1083              } catch (InterruptedException ok) {}
1084              return Boolean.TRUE;
# Line 956 | Line 1125 | public class JSR166TestCase extends Test
1125      }
1126  
1127      /**
1128 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1129 <     * of throwing checked exceptions.
1128 >     * A CyclicBarrier that uses timed await and fails with
1129 >     * AssertionFailedErrors instead of throwing checked exceptions.
1130       */
1131      public class CheckedBarrier extends CyclicBarrier {
1132          public CheckedBarrier(int parties) { super(parties); }
1133  
1134          public int await() {
1135              try {
1136 <                return super.await();
1136 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1137 >            } catch (TimeoutException e) {
1138 >                throw new AssertionFailedError("timed out");
1139              } catch (Exception e) {
1140                  AssertionFailedError afe =
1141                      new AssertionFailedError("Unexpected exception: " + e);
# Line 974 | Line 1145 | public class JSR166TestCase extends Test
1145          }
1146      }
1147  
1148 +    void checkEmpty(BlockingQueue q) {
1149 +        try {
1150 +            assertTrue(q.isEmpty());
1151 +            assertEquals(0, q.size());
1152 +            assertNull(q.peek());
1153 +            assertNull(q.poll());
1154 +            assertNull(q.poll(0, MILLISECONDS));
1155 +            assertEquals(q.toString(), "[]");
1156 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1157 +            assertFalse(q.iterator().hasNext());
1158 +            try {
1159 +                q.element();
1160 +                shouldThrow();
1161 +            } catch (NoSuchElementException success) {}
1162 +            try {
1163 +                q.iterator().next();
1164 +                shouldThrow();
1165 +            } catch (NoSuchElementException success) {}
1166 +            try {
1167 +                q.remove();
1168 +                shouldThrow();
1169 +            } catch (NoSuchElementException success) {}
1170 +        } catch (InterruptedException ie) {
1171 +            threadUnexpectedException(ie);
1172 +        }
1173 +    }
1174 +
1175 +    @SuppressWarnings("unchecked")
1176 +    <T> T serialClone(T o) {
1177 +        try {
1178 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1179 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1180 +            oos.writeObject(o);
1181 +            oos.flush();
1182 +            oos.close();
1183 +            ObjectInputStream ois = new ObjectInputStream
1184 +                (new ByteArrayInputStream(bos.toByteArray()));
1185 +            T clone = (T) ois.readObject();
1186 +            assertSame(o.getClass(), clone.getClass());
1187 +            return clone;
1188 +        } catch (Throwable t) {
1189 +            threadUnexpectedException(t);
1190 +            return null;
1191 +        }
1192 +    }
1193   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines