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.80 by jsr166, Fri May 13 21:48:58 2011 UTC vs.
Revision 1.89 by jsr166, Fri Jun 3 05:07:14 2011 UTC

# Line 12 | Line 12 | 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 258 | Line 260 | public class JSR166TestCase extends Test
260          return 50;
261      }
262  
261
263      /**
264       * Sets delays as multiples of SHORT_DELAY.
265       */
# Line 270 | 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 290 | 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 310 | 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 441 | 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
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 <    public static void delay(long millis) throws InterruptedException {
478 >    static void delay(long millis) throws InterruptedException {
479          long startTime = System.nanoTime();
480          long ns = millis * 1000 * 1000;
481          for (;;) {
# Line 470 | Line 494 | public class JSR166TestCase extends Test
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 483 | Line 507 | public class JSR166TestCase extends Test
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 <    public void assertThreadStaysAlive(Thread thread, long millis) {
520 >    void assertThreadStaysAlive(Thread thread, long millis) {
521          try {
522              // No need to optimize the failing case via Thread.join.
523              delay(millis);
# Line 496 | Line 528 | public class JSR166TestCase extends Test
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".
555       */
556      public void shouldThrow() {
# Line 635 | Line 690 | public class JSR166TestCase extends Test
690      }
691  
692      /**
693 <     * Sleeps until the timeout has elapsed, or interrupted.
639 <     * Does <em>NOT</em> throw InterruptedException.
640 <     */
641 <    void sleepTillInterrupted(long timeoutMillis) {
642 <        try {
643 <            Thread.sleep(timeoutMillis);
644 <        } catch (InterruptedException wakeup) {}
645 <    }
646 <
647 <    /**
648 <     * Waits up to the specified number of milliseconds for the given
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 waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
697 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 <        long t0 = System.nanoTime();
697 >        long startTime = System.nanoTime();
698          for (;;) {
699              Thread.State s = thread.getState();
700              if (s == Thread.State.BLOCKED ||
# Line 659 | Line 703 | public class JSR166TestCase extends Test
703                  return;
704              else if (s == Thread.State.TERMINATED)
705                  fail("Unexpected thread termination");
706 <            else if (System.nanoTime() - t0 > timeoutNanos) {
706 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
707                  threadAssertTrue(thread.isAlive());
708                  return;
709              }
# Line 705 | 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              }
# Line 783 | 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 812 | 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 858 | Line 904 | public class JSR166TestCase extends Test
904          }
905      }
906  
907 +    public void await(Semaphore semaphore) {
908 +        try {
909 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
910 +        } catch (Throwable t) {
911 +            threadUnexpectedException(t);
912 +        }
913 +    }
914 +
915 + //     /**
916 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
917 + //      */
918 + //     public void await(AtomicBoolean flag) {
919 + //         await(flag, LONG_DELAY_MS);
920 + //     }
921 +
922 + //     /**
923 + //      * Spin-waits up to the specified timeout until flag becomes true.
924 + //      */
925 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
926 + //         long startTime = System.nanoTime();
927 + //         while (!flag.get()) {
928 + //             if (millisElapsedSince(startTime) > timeoutMillis)
929 + //                 throw new AssertionFailedError("timed out");
930 + //             Thread.yield();
931 + //         }
932 + //     }
933 +
934      public static class NPETask implements Callable<String> {
935          public String call() { throw new NullPointerException(); }
936      }
# Line 1060 | Line 1133 | public class JSR166TestCase extends Test
1133      }
1134  
1135      /**
1136 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1137 <     * of throwing checked exceptions.
1136 >     * A CyclicBarrier that uses timed await and fails with
1137 >     * AssertionFailedErrors instead of throwing checked exceptions.
1138       */
1139      public class CheckedBarrier extends CyclicBarrier {
1140          public CheckedBarrier(int parties) { super(parties); }
1141  
1142          public int await() {
1143              try {
1144 <                return super.await();
1144 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1145 >            } catch (TimeoutException e) {
1146 >                throw new AssertionFailedError("timed out");
1147              } catch (Exception e) {
1148                  AssertionFailedError afe =
1149                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1078 | Line 1153 | public class JSR166TestCase extends Test
1153          }
1154      }
1155  
1156 <    public void checkEmpty(BlockingQueue q) {
1156 >    void checkEmpty(BlockingQueue q) {
1157          try {
1158              assertTrue(q.isEmpty());
1159              assertEquals(0, q.size());
# Line 1106 | Line 1181 | public class JSR166TestCase extends Test
1181      }
1182  
1183      @SuppressWarnings("unchecked")
1184 <    public <T> T serialClone(T o) {
1184 >    <T> T serialClone(T o) {
1185          try {
1186              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1187              ObjectOutputStream oos = new ObjectOutputStream(bos);
1188              oos.writeObject(o);
1189              oos.flush();
1190              oos.close();
1191 <            ByteArrayInputStream bin =
1192 <                new ByteArrayInputStream(bos.toByteArray());
1193 <            ObjectInputStream ois = new ObjectInputStream(bin);
1194 <            return (T) ois.readObject();
1191 >            ObjectInputStream ois = new ObjectInputStream
1192 >                (new ByteArrayInputStream(bos.toByteArray()));
1193 >            T clone = (T) ois.readObject();
1194 >            assertSame(o.getClass(), clone.getClass());
1195 >            return clone;
1196          } catch (Throwable t) {
1197              threadUnexpectedException(t);
1198              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines