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.74 by jsr166, Tue Mar 15 19:47:06 2011 UTC vs.
Revision 1.83 by jsr166, Fri May 27 19:29:59 2011 UTC

# Line 7 | Line 7
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 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(new Date().getTime() + delayMillis);
287 +    }
288 +
289 +    /**
290       * The first exception encountered if any threadAssertXXX method fails.
291       */
292      private final AtomicReference<Throwable> threadFailure
# Line 437 | Line 458 | public class JSR166TestCase extends Test
458          else {
459              AssertionFailedError afe =
460                  new AssertionFailedError("unexpected exception: " + t);
461 <            t.initCause(t);
461 >            afe.initCause(t);
462              throw afe;
463          }
464      }
465  
466      /**
467 +     * Delays, via Thread.sleep, for the given millisecond delay, but
468 +     * if the sleep is shorter than specified, may re-sleep or yield
469 +     * until time elapses.
470 +     */
471 +    static void delay(long millis) throws InterruptedException {
472 +        long startTime = System.nanoTime();
473 +        long ns = millis * 1000 * 1000;
474 +        for (;;) {
475 +            if (millis > 0L)
476 +                Thread.sleep(millis);
477 +            else // too short to sleep
478 +                Thread.yield();
479 +            long d = ns - (System.nanoTime() - startTime);
480 +            if (d > 0L)
481 +                millis = d / (1000 * 1000);
482 +            else
483 +                break;
484 +        }
485 +    }
486 +
487 +    /**
488       * Waits out termination of a thread pool or fails doing so.
489       */
490 <    public void joinPool(ExecutorService exec) {
490 >    void joinPool(ExecutorService exec) {
491          try {
492              exec.shutdown();
493              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 457 | Line 499 | public class JSR166TestCase extends Test
499          }
500      }
501  
502 +    /**
503 +     * Checks that thread does not terminate within the default
504 +     * millisecond delay of {@code timeoutMillis()}.
505 +     */
506 +    void assertThreadStaysAlive(Thread thread) {
507 +        assertThreadStaysAlive(thread, timeoutMillis());
508 +    }
509 +
510 +    /**
511 +     * Checks that thread does not terminate within the given millisecond delay.
512 +     */
513 +    void assertThreadStaysAlive(Thread thread, long millis) {
514 +        try {
515 +            // No need to optimize the failing case via Thread.join.
516 +            delay(millis);
517 +            assertTrue(thread.isAlive());
518 +        } catch (InterruptedException ie) {
519 +            fail("Unexpected InterruptedException");
520 +        }
521 +    }
522 +
523 +    /**
524 +     * Checks that future.get times out, with the default timeout of
525 +     * {@code timeoutMillis()}.
526 +     */
527 +    void assertFutureTimesOut(Future future) {
528 +        assertFutureTimesOut(future, timeoutMillis());
529 +    }
530 +
531 +    /**
532 +     * Checks that future.get times out, with the given millisecond timeout.
533 +     */
534 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
535 +        long startTime = System.nanoTime();
536 +        try {
537 +            future.get(timeoutMillis, MILLISECONDS);
538 +            shouldThrow();
539 +        } catch (TimeoutException success) {
540 +        } catch (Exception e) {
541 +            threadUnexpectedException(e);
542 +        } finally { future.cancel(true); }
543 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
544 +    }
545  
546      /**
547       * Fails with message "should throw exception".
# Line 588 | Line 673 | public class JSR166TestCase extends Test
673       */
674      void sleep(long millis) {
675          try {
676 <            Thread.sleep(millis);
676 >            delay(millis);
677          } catch (InterruptedException ie) {
678              AssertionFailedError afe =
679                  new AssertionFailedError("Unexpected InterruptedException");
# Line 598 | Line 683 | public class JSR166TestCase extends Test
683      }
684  
685      /**
601     * 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    /**
686       * Waits up to the specified number of milliseconds for the given
687       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
688       */
# Line 631 | Line 706 | public class JSR166TestCase extends Test
706      }
707  
708      /**
709 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
710 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
711 +     */
712 +    void waitForThreadToEnterWaitState(Thread thread) {
713 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
714 +    }
715 +
716 +    /**
717       * Returns the number of milliseconds since time given by
718       * startNanoTime, which must have been previously returned from a
719       * call to {@link System.nanoTime()}.
# Line 660 | Line 743 | public class JSR166TestCase extends Test
743          } catch (InterruptedException ie) {
744              threadUnexpectedException(ie);
745          } finally {
746 <            if (t.isAlive()) {
746 >            if (t.getState() != Thread.State.TERMINATED) {
747                  t.interrupt();
748                  fail("Test timed out");
749              }
750          }
751      }
752  
753 +    /**
754 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
755 +     * terminate (using {@link Thread#join(long)}), else interrupts
756 +     * the thread (in the hope that it may terminate later) and fails.
757 +     */
758 +    void awaitTermination(Thread t) {
759 +        awaitTermination(t, LONG_DELAY_MS);
760 +    }
761 +
762      // Some convenient Runnable classes
763  
764      public abstract class CheckedRunnable implements Runnable {
# Line 729 | Line 821 | public class JSR166TestCase extends Test
821                  realRun();
822                  threadShouldThrow("InterruptedException");
823              } catch (InterruptedException success) {
824 +                threadAssertFalse(Thread.interrupted());
825              } catch (Throwable t) {
826                  threadUnexpectedException(t);
827              }
# Line 758 | Line 851 | public class JSR166TestCase extends Test
851                  threadShouldThrow("InterruptedException");
852                  return result;
853              } catch (InterruptedException success) {
854 +                threadAssertFalse(Thread.interrupted());
855              } catch (Throwable t) {
856                  threadUnexpectedException(t);
857              }
# Line 792 | Line 886 | public class JSR166TestCase extends Test
886      public Runnable awaiter(final CountDownLatch latch) {
887          return new CheckedRunnable() {
888              public void realRun() throws InterruptedException {
889 <                latch.await();
889 >                await(latch);
890              }};
891      }
892  
893 +    public void await(CountDownLatch latch) {
894 +        try {
895 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
896 +        } catch (Throwable t) {
897 +            threadUnexpectedException(t);
898 +        }
899 +    }
900 +
901 + //     /**
902 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
903 + //      */
904 + //     public void await(AtomicBoolean flag) {
905 + //         await(flag, LONG_DELAY_MS);
906 + //     }
907 +
908 + //     /**
909 + //      * Spin-waits up to the specified timeout until flag becomes true.
910 + //      */
911 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
912 + //         long startTime = System.nanoTime();
913 + //         while (!flag.get()) {
914 + //             if (millisElapsedSince(startTime) > timeoutMillis)
915 + //                 throw new AssertionFailedError("timed out");
916 + //             Thread.yield();
917 + //         }
918 + //     }
919 +
920      public static class NPETask implements Callable<String> {
921          public String call() { throw new NullPointerException(); }
922      }
# Line 806 | Line 927 | public class JSR166TestCase extends Test
927  
928      public class ShortRunnable extends CheckedRunnable {
929          protected void realRun() throws Throwable {
930 <            Thread.sleep(SHORT_DELAY_MS);
930 >            delay(SHORT_DELAY_MS);
931          }
932      }
933  
934      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
935          protected void realRun() throws InterruptedException {
936 <            Thread.sleep(SHORT_DELAY_MS);
936 >            delay(SHORT_DELAY_MS);
937          }
938      }
939  
940      public class SmallRunnable extends CheckedRunnable {
941          protected void realRun() throws Throwable {
942 <            Thread.sleep(SMALL_DELAY_MS);
942 >            delay(SMALL_DELAY_MS);
943          }
944      }
945  
946      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
947          protected void realRun() {
948              try {
949 <                Thread.sleep(SMALL_DELAY_MS);
949 >                delay(SMALL_DELAY_MS);
950              } catch (InterruptedException ok) {}
951          }
952      }
953  
954      public class SmallCallable extends CheckedCallable {
955          protected Object realCall() throws InterruptedException {
956 <            Thread.sleep(SMALL_DELAY_MS);
956 >            delay(SMALL_DELAY_MS);
957              return Boolean.TRUE;
958          }
959      }
960  
961      public class MediumRunnable extends CheckedRunnable {
962          protected void realRun() throws Throwable {
963 <            Thread.sleep(MEDIUM_DELAY_MS);
963 >            delay(MEDIUM_DELAY_MS);
964          }
965      }
966  
967      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
968          protected void realRun() throws InterruptedException {
969 <            Thread.sleep(MEDIUM_DELAY_MS);
969 >            delay(MEDIUM_DELAY_MS);
970          }
971      }
972  
# Line 853 | Line 974 | public class JSR166TestCase extends Test
974          return new CheckedRunnable() {
975              protected void realRun() {
976                  try {
977 <                    Thread.sleep(timeoutMillis);
977 >                    delay(timeoutMillis);
978                  } catch (InterruptedException ok) {}
979              }};
980      }
# Line 861 | Line 982 | public class JSR166TestCase extends Test
982      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
983          protected void realRun() {
984              try {
985 <                Thread.sleep(MEDIUM_DELAY_MS);
985 >                delay(MEDIUM_DELAY_MS);
986              } catch (InterruptedException ok) {}
987          }
988      }
# Line 869 | Line 990 | public class JSR166TestCase extends Test
990      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
991          protected void realRun() {
992              try {
993 <                Thread.sleep(LONG_DELAY_MS);
993 >                delay(LONG_DELAY_MS);
994              } catch (InterruptedException ok) {}
995          }
996      }
# Line 893 | Line 1014 | public class JSR166TestCase extends Test
1014                  public boolean isDone() { return done; }
1015                  public void run() {
1016                      try {
1017 <                        Thread.sleep(timeoutMillis);
1017 >                        delay(timeoutMillis);
1018                          done = true;
1019                      } catch (InterruptedException ok) {}
1020                  }
# Line 904 | Line 1025 | public class JSR166TestCase extends Test
1025          public volatile boolean done = false;
1026          public void run() {
1027              try {
1028 <                Thread.sleep(SHORT_DELAY_MS);
1028 >                delay(SHORT_DELAY_MS);
1029                  done = true;
1030              } catch (InterruptedException ok) {}
1031          }
# Line 914 | Line 1035 | public class JSR166TestCase extends Test
1035          public volatile boolean done = false;
1036          public void run() {
1037              try {
1038 <                Thread.sleep(SMALL_DELAY_MS);
1038 >                delay(SMALL_DELAY_MS);
1039                  done = true;
1040              } catch (InterruptedException ok) {}
1041          }
# Line 924 | Line 1045 | public class JSR166TestCase extends Test
1045          public volatile boolean done = false;
1046          public void run() {
1047              try {
1048 <                Thread.sleep(MEDIUM_DELAY_MS);
1048 >                delay(MEDIUM_DELAY_MS);
1049                  done = true;
1050              } catch (InterruptedException ok) {}
1051          }
# Line 934 | Line 1055 | public class JSR166TestCase extends Test
1055          public volatile boolean done = false;
1056          public void run() {
1057              try {
1058 <                Thread.sleep(LONG_DELAY_MS);
1058 >                delay(LONG_DELAY_MS);
1059                  done = true;
1060              } catch (InterruptedException ok) {}
1061          }
# Line 951 | Line 1072 | public class JSR166TestCase extends Test
1072          public volatile boolean done = false;
1073          public Object call() {
1074              try {
1075 <                Thread.sleep(SMALL_DELAY_MS);
1075 >                delay(SMALL_DELAY_MS);
1076                  done = true;
1077              } catch (InterruptedException ok) {}
1078              return Boolean.TRUE;
# Line 1016 | Line 1137 | public class JSR166TestCase extends Test
1137          }
1138      }
1139  
1140 <    public void checkEmpty(BlockingQueue q) {
1140 >    void checkEmpty(BlockingQueue q) {
1141          try {
1142              assertTrue(q.isEmpty());
1143              assertEquals(0, q.size());
# Line 1043 | Line 1164 | public class JSR166TestCase extends Test
1164          }
1165      }
1166  
1167 +    @SuppressWarnings("unchecked")
1168 +    <T> T serialClone(T o) {
1169 +        try {
1170 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1171 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1172 +            oos.writeObject(o);
1173 +            oos.flush();
1174 +            oos.close();
1175 +            ByteArrayInputStream bin =
1176 +                new ByteArrayInputStream(bos.toByteArray());
1177 +            ObjectInputStream ois = new ObjectInputStream(bin);
1178 +            return (T) ois.readObject();
1179 +        } catch (Throwable t) {
1180 +            threadUnexpectedException(t);
1181 +            return null;
1182 +        }
1183 +    }
1184   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines