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.64 by jsr166, Fri Oct 15 22:30:07 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 259 | 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 288 | 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 440 | 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 454 | 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 585 | 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 605 | 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 632 | 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 754 | 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 764 | 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  
# Line 811 | Line 915 | public class JSR166TestCase extends Test
915          return new CheckedRunnable() {
916              protected void realRun() {
917                  try {
918 <                    Thread.sleep(timeoutMillis);
918 >                    delay(timeoutMillis);
919                  } catch (InterruptedException ok) {}
920              }};
921      }
# Line 819 | Line 923 | public class JSR166TestCase extends Test
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 827 | 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 851 | Line 955 | public class JSR166TestCase extends Test
955                  public boolean isDone() { return done; }
956                  public void run() {
957                      try {
958 <                        Thread.sleep(timeoutMillis);
958 >                        delay(timeoutMillis);
959                          done = true;
960                      } catch (InterruptedException ok) {}
961                  }
# Line 862 | Line 966 | public class JSR166TestCase extends Test
966          public volatile boolean done = false;
967          public void run() {
968              try {
969 <                Thread.sleep(SHORT_DELAY_MS);
969 >                delay(SHORT_DELAY_MS);
970                  done = true;
971              } catch (InterruptedException ok) {}
972          }
# Line 872 | Line 976 | public class JSR166TestCase extends Test
976          public volatile boolean done = false;
977          public void run() {
978              try {
979 <                Thread.sleep(SMALL_DELAY_MS);
979 >                delay(SMALL_DELAY_MS);
980                  done = true;
981              } catch (InterruptedException ok) {}
982          }
# Line 882 | 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 892 | 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 909 | 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 974 | 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