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.73 by jsr166, Mon Nov 29 07:39:53 2010 UTC vs.
Revision 1.92 by jsr166, Sun Nov 18 18:03:11 2012 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;
# Line 63 | Line 69 | import java.security.SecurityPermission;
69   *
70   * </ol>
71   *
72 < * <p> <b>Other notes</b>
72 > * <p><b>Other notes</b>
73   * <ul>
74   *
75   * <li> Usually, there is one testcase method per JSR166 method
# Line 254 | Line 260 | public class JSR166TestCase extends Test
260          return 50;
261      }
262  
257
263      /**
264       * Sets delays as multiples of SHORT_DELAY.
265       */
# Line 266 | Line 271 | public class JSR166TestCase extends Test
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 +    /**
290       * The first exception encountered if any threadAssertXXX method fails.
291       */
292      private final AtomicReference<Throwable> threadFailure
# Line 286 | 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.getAndSet(null);
# Line 306 | 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 437 | 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",
# Line 457 | 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 the threads do not terminate within the default
532 +     * millisecond delay of {@code timeoutMillis()}.
533 +     */
534 +    void assertThreadsStayAlive(Thread... threads) {
535 +        assertThreadsStayAlive(timeoutMillis(), threads);
536 +    }
537 +
538 +    /**
539 +     * Checks that the threads do not terminate within the given millisecond delay.
540 +     */
541 +    void assertThreadsStayAlive(long millis, Thread... threads) {
542 +        try {
543 +            // No need to optimize the failing case via Thread.join.
544 +            delay(millis);
545 +            for (Thread thread : threads)
546 +                assertTrue(thread.isAlive());
547 +        } catch (InterruptedException ie) {
548 +            fail("Unexpected InterruptedException");
549 +        }
550 +    }
551 +
552 +    /**
553 +     * Checks that future.get times out, with the default timeout of
554 +     * {@code timeoutMillis()}.
555 +     */
556 +    void assertFutureTimesOut(Future future) {
557 +        assertFutureTimesOut(future, timeoutMillis());
558 +    }
559 +
560 +    /**
561 +     * Checks that future.get times out, with the given millisecond timeout.
562 +     */
563 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
564 +        long startTime = System.nanoTime();
565 +        try {
566 +            future.get(timeoutMillis, MILLISECONDS);
567 +            shouldThrow();
568 +        } catch (TimeoutException success) {
569 +        } catch (Exception e) {
570 +            threadUnexpectedException(e);
571 +        } finally { future.cancel(true); }
572 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
573 +    }
574  
575      /**
576       * Fails with message "should throw exception".
# Line 588 | Line 702 | public class JSR166TestCase extends Test
702       */
703      void sleep(long millis) {
704          try {
705 <            Thread.sleep(millis);
705 >            delay(millis);
706          } catch (InterruptedException ie) {
707              AssertionFailedError afe =
708                  new AssertionFailedError("Unexpected InterruptedException");
# Line 598 | Line 712 | public class JSR166TestCase extends Test
712      }
713  
714      /**
715 <     * Sleeps until the timeout has elapsed, or interrupted.
602 <     * Does <em>NOT</em> throw InterruptedException.
603 <     */
604 <    void sleepTillInterrupted(long timeoutMillis) {
605 <        try {
606 <            Thread.sleep(timeoutMillis);
607 <        } catch (InterruptedException wakeup) {}
608 <    }
609 <
610 <    /**
611 <     * Waits up to the specified number of milliseconds for the given
715 >     * Spin-waits up to the specified number of milliseconds for the given
716       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
717       */
718      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
719 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
616 <        long t0 = System.nanoTime();
719 >        long startTime = System.nanoTime();
720          for (;;) {
721              Thread.State s = thread.getState();
722              if (s == Thread.State.BLOCKED ||
# Line 622 | Line 725 | public class JSR166TestCase extends Test
725                  return;
726              else if (s == Thread.State.TERMINATED)
727                  fail("Unexpected thread termination");
728 <            else if (System.nanoTime() - t0 > timeoutNanos) {
728 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
729                  threadAssertTrue(thread.isAlive());
730                  return;
731              }
# Line 631 | Line 734 | public class JSR166TestCase extends Test
734      }
735  
736      /**
737 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
738 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
739 +     */
740 +    void waitForThreadToEnterWaitState(Thread thread) {
741 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
742 +    }
743 +
744 +    /**
745       * Returns the number of milliseconds since time given by
746       * startNanoTime, which must have been previously returned from a
747       * call to {@link System.nanoTime()}.
# Line 660 | Line 771 | public class JSR166TestCase extends Test
771          } catch (InterruptedException ie) {
772              threadUnexpectedException(ie);
773          } finally {
774 <            if (t.isAlive()) {
774 >            if (t.getState() != Thread.State.TERMINATED) {
775                  t.interrupt();
776                  fail("Test timed out");
777              }
778          }
779      }
780  
781 +    /**
782 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
783 +     * terminate (using {@link Thread#join(long)}), else interrupts
784 +     * the thread (in the hope that it may terminate later) and fails.
785 +     */
786 +    void awaitTermination(Thread t) {
787 +        awaitTermination(t, LONG_DELAY_MS);
788 +    }
789 +
790      // Some convenient Runnable classes
791  
792      public abstract class CheckedRunnable implements Runnable {
# Line 729 | Line 849 | public class JSR166TestCase extends Test
849                  realRun();
850                  threadShouldThrow("InterruptedException");
851              } catch (InterruptedException success) {
852 +                threadAssertFalse(Thread.interrupted());
853              } catch (Throwable t) {
854                  threadUnexpectedException(t);
855              }
# Line 758 | Line 879 | public class JSR166TestCase extends Test
879                  threadShouldThrow("InterruptedException");
880                  return result;
881              } catch (InterruptedException success) {
882 +                threadAssertFalse(Thread.interrupted());
883              } catch (Throwable t) {
884                  threadUnexpectedException(t);
885              }
# Line 792 | Line 914 | public class JSR166TestCase extends Test
914      public Runnable awaiter(final CountDownLatch latch) {
915          return new CheckedRunnable() {
916              public void realRun() throws InterruptedException {
917 <                latch.await();
917 >                await(latch);
918              }};
919      }
920  
921 +    public void await(CountDownLatch latch) {
922 +        try {
923 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
924 +        } catch (Throwable t) {
925 +            threadUnexpectedException(t);
926 +        }
927 +    }
928 +
929 +    public void await(Semaphore semaphore) {
930 +        try {
931 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
932 +        } catch (Throwable t) {
933 +            threadUnexpectedException(t);
934 +        }
935 +    }
936 +
937 + //     /**
938 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
939 + //      */
940 + //     public void await(AtomicBoolean flag) {
941 + //         await(flag, LONG_DELAY_MS);
942 + //     }
943 +
944 + //     /**
945 + //      * Spin-waits up to the specified timeout until flag becomes true.
946 + //      */
947 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
948 + //         long startTime = System.nanoTime();
949 + //         while (!flag.get()) {
950 + //             if (millisElapsedSince(startTime) > timeoutMillis)
951 + //                 throw new AssertionFailedError("timed out");
952 + //             Thread.yield();
953 + //         }
954 + //     }
955 +
956      public static class NPETask implements Callable<String> {
957          public String call() { throw new NullPointerException(); }
958      }
# Line 806 | Line 963 | public class JSR166TestCase extends Test
963  
964      public class ShortRunnable extends CheckedRunnable {
965          protected void realRun() throws Throwable {
966 <            Thread.sleep(SHORT_DELAY_MS);
966 >            delay(SHORT_DELAY_MS);
967          }
968      }
969  
970      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
971          protected void realRun() throws InterruptedException {
972 <            Thread.sleep(SHORT_DELAY_MS);
972 >            delay(SHORT_DELAY_MS);
973          }
974      }
975  
976      public class SmallRunnable extends CheckedRunnable {
977          protected void realRun() throws Throwable {
978 <            Thread.sleep(SMALL_DELAY_MS);
978 >            delay(SMALL_DELAY_MS);
979          }
980      }
981  
982      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
983          protected void realRun() {
984              try {
985 <                Thread.sleep(SMALL_DELAY_MS);
985 >                delay(SMALL_DELAY_MS);
986              } catch (InterruptedException ok) {}
987          }
988      }
989  
990      public class SmallCallable extends CheckedCallable {
991          protected Object realCall() throws InterruptedException {
992 <            Thread.sleep(SMALL_DELAY_MS);
992 >            delay(SMALL_DELAY_MS);
993              return Boolean.TRUE;
994          }
995      }
996  
997      public class MediumRunnable extends CheckedRunnable {
998          protected void realRun() throws Throwable {
999 <            Thread.sleep(MEDIUM_DELAY_MS);
999 >            delay(MEDIUM_DELAY_MS);
1000          }
1001      }
1002  
1003      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1004          protected void realRun() throws InterruptedException {
1005 <            Thread.sleep(MEDIUM_DELAY_MS);
1005 >            delay(MEDIUM_DELAY_MS);
1006          }
1007      }
1008  
# Line 853 | Line 1010 | public class JSR166TestCase extends Test
1010          return new CheckedRunnable() {
1011              protected void realRun() {
1012                  try {
1013 <                    Thread.sleep(timeoutMillis);
1013 >                    delay(timeoutMillis);
1014                  } catch (InterruptedException ok) {}
1015              }};
1016      }
# Line 861 | Line 1018 | public class JSR166TestCase extends Test
1018      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1019          protected void realRun() {
1020              try {
1021 <                Thread.sleep(MEDIUM_DELAY_MS);
1021 >                delay(MEDIUM_DELAY_MS);
1022              } catch (InterruptedException ok) {}
1023          }
1024      }
# Line 869 | Line 1026 | public class JSR166TestCase extends Test
1026      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1027          protected void realRun() {
1028              try {
1029 <                Thread.sleep(LONG_DELAY_MS);
1029 >                delay(LONG_DELAY_MS);
1030              } catch (InterruptedException ok) {}
1031          }
1032      }
# Line 893 | Line 1050 | public class JSR166TestCase extends Test
1050                  public boolean isDone() { return done; }
1051                  public void run() {
1052                      try {
1053 <                        Thread.sleep(timeoutMillis);
1053 >                        delay(timeoutMillis);
1054                          done = true;
1055                      } catch (InterruptedException ok) {}
1056                  }
# Line 904 | Line 1061 | public class JSR166TestCase extends Test
1061          public volatile boolean done = false;
1062          public void run() {
1063              try {
1064 <                Thread.sleep(SHORT_DELAY_MS);
1064 >                delay(SHORT_DELAY_MS);
1065                  done = true;
1066              } catch (InterruptedException ok) {}
1067          }
# Line 914 | Line 1071 | public class JSR166TestCase extends Test
1071          public volatile boolean done = false;
1072          public void run() {
1073              try {
1074 <                Thread.sleep(SMALL_DELAY_MS);
1074 >                delay(SMALL_DELAY_MS);
1075                  done = true;
1076              } catch (InterruptedException ok) {}
1077          }
# Line 924 | Line 1081 | public class JSR166TestCase extends Test
1081          public volatile boolean done = false;
1082          public void run() {
1083              try {
1084 <                Thread.sleep(MEDIUM_DELAY_MS);
1084 >                delay(MEDIUM_DELAY_MS);
1085                  done = true;
1086              } catch (InterruptedException ok) {}
1087          }
# Line 934 | Line 1091 | public class JSR166TestCase extends Test
1091          public volatile boolean done = false;
1092          public void run() {
1093              try {
1094 <                Thread.sleep(LONG_DELAY_MS);
1094 >                delay(LONG_DELAY_MS);
1095                  done = true;
1096              } catch (InterruptedException ok) {}
1097          }
# Line 951 | Line 1108 | public class JSR166TestCase extends Test
1108          public volatile boolean done = false;
1109          public Object call() {
1110              try {
1111 <                Thread.sleep(SMALL_DELAY_MS);
1111 >                delay(SMALL_DELAY_MS);
1112                  done = true;
1113              } catch (InterruptedException ok) {}
1114              return Boolean.TRUE;
# Line 998 | Line 1155 | public class JSR166TestCase extends Test
1155      }
1156  
1157      /**
1158 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1159 <     * of throwing checked exceptions.
1158 >     * A CyclicBarrier that uses timed await and fails with
1159 >     * AssertionFailedErrors instead of throwing checked exceptions.
1160       */
1161      public class CheckedBarrier extends CyclicBarrier {
1162          public CheckedBarrier(int parties) { super(parties); }
1163  
1164          public int await() {
1165              try {
1166 <                return super.await();
1166 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1167 >            } catch (TimeoutException e) {
1168 >                throw new AssertionFailedError("timed out");
1169              } catch (Exception e) {
1170                  AssertionFailedError afe =
1171                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1016 | Line 1175 | public class JSR166TestCase extends Test
1175          }
1176      }
1177  
1178 <    public void checkEmpty(BlockingQueue q) {
1178 >    void checkEmpty(BlockingQueue q) {
1179          try {
1180              assertTrue(q.isEmpty());
1181              assertEquals(0, q.size());
# Line 1043 | Line 1202 | public class JSR166TestCase extends Test
1202          }
1203      }
1204  
1205 +    void assertSerialEquals(Object x, Object y) {
1206 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1207 +    }
1208 +
1209 +    void assertNotSerialEquals(Object x, Object y) {
1210 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1211 +    }
1212 +
1213 +    byte[] serialBytes(Object o) {
1214 +        try {
1215 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1216 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1217 +            oos.writeObject(o);
1218 +            oos.flush();
1219 +            oos.close();
1220 +            return bos.toByteArray();
1221 +        } catch (Throwable t) {
1222 +            threadUnexpectedException(t);
1223 +            return new byte[0];
1224 +        }
1225 +    }
1226 +
1227 +    @SuppressWarnings("unchecked")
1228 +    <T> T serialClone(T o) {
1229 +        try {
1230 +            ObjectInputStream ois = new ObjectInputStream
1231 +                (new ByteArrayInputStream(serialBytes(o)));
1232 +            T clone = (T) ois.readObject();
1233 +            assertSame(o.getClass(), clone.getClass());
1234 +            return clone;
1235 +        } catch (Throwable t) {
1236 +            threadUnexpectedException(t);
1237 +            return null;
1238 +        }
1239 +    }
1240   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines