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.79 by jsr166, Mon May 9 20:00:19 2011 UTC vs.
Revision 1.90 by jsr166, Wed Jun 22 07:46:57 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 ms) throws InterruptedException {
478 >    static void delay(long millis) throws InterruptedException {
479          long startTime = System.nanoTime();
480 <        long ns = ms * 1000 * 1000;
480 >        long ns = millis * 1000 * 1000;
481          for (;;) {
482 <            if (ms > 0L)
483 <                Thread.sleep(ms);
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 <                ms = d / (1000 * 1000);
488 >                millis = d / (1000 * 1000);
489              else
490                  break;
491          }
# 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 timeoutMillis
511 <     * milliseconds (that is, Thread.join times out).
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 assertThreadJoinTimesOut(Thread thread, long timeoutMillis) {
520 >    void assertThreadStaysAlive(Thread thread, long millis) {
521          try {
522 <            long startTime = System.nanoTime();
523 <            thread.join(timeoutMillis);
522 >            // No need to optimize the failing case via Thread.join.
523 >            delay(millis);
524              assertTrue(thread.isAlive());
494            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
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".
577       */
578      public void shouldThrow() {
# Line 637 | Line 712 | public class JSR166TestCase extends Test
712      }
713  
714      /**
715 <     * Sleeps until the timeout has elapsed, or interrupted.
641 <     * Does <em>NOT</em> throw InterruptedException.
642 <     */
643 <    void sleepTillInterrupted(long timeoutMillis) {
644 <        try {
645 <            Thread.sleep(timeoutMillis);
646 <        } catch (InterruptedException wakeup) {}
647 <    }
648 <
649 <    /**
650 <     * 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;
655 <        long t0 = System.nanoTime();
719 >        long startTime = System.nanoTime();
720          for (;;) {
721              Thread.State s = thread.getState();
722              if (s == Thread.State.BLOCKED ||
# Line 661 | 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 707 | 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              }
# Line 785 | 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 814 | 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 860 | Line 926 | public class JSR166TestCase extends Test
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 1062 | 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 1080 | 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 1108 | Line 1203 | public class JSR166TestCase extends Test
1203      }
1204  
1205      @SuppressWarnings("unchecked")
1206 <    public <T> T serialClone(T o) {
1206 >    <T> T serialClone(T o) {
1207          try {
1208              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1209              ObjectOutputStream oos = new ObjectOutputStream(bos);
1210              oos.writeObject(o);
1211              oos.flush();
1212              oos.close();
1213 <            ByteArrayInputStream bin =
1214 <                new ByteArrayInputStream(bos.toByteArray());
1215 <            ObjectInputStream ois = new ObjectInputStream(bin);
1216 <            return (T) ois.readObject();
1213 >            ObjectInputStream ois = new ObjectInputStream
1214 >                (new ByteArrayInputStream(bos.toByteArray()));
1215 >            T clone = (T) ois.readObject();
1216 >            assertSame(o.getClass(), clone.getClass());
1217 >            return clone;
1218          } catch (Throwable t) {
1219              threadUnexpectedException(t);
1220              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines