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.76 by dl, Fri May 6 11:22:07 2011 UTC vs.
Revision 1.87 by jsr166, Mon May 30 22:53:21 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(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
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 466 | 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 478 | 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 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".
# Line 619 | Line 690 | public class JSR166TestCase extends Test
690      }
691  
692      /**
622     * Sleeps until the timeout has elapsed, or interrupted.
623     * Does <em>NOT</em> throw InterruptedException.
624     */
625    void sleepTillInterrupted(long timeoutMillis) {
626        try {
627            Thread.sleep(timeoutMillis);
628        } catch (InterruptedException wakeup) {}
629    }
630
631    /**
693       * Waits up to the specified number of milliseconds for the given
694       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
695       */
# Line 689 | Line 750 | public class JSR166TestCase extends Test
750          } catch (InterruptedException ie) {
751              threadUnexpectedException(ie);
752          } finally {
753 <            if (t.isAlive()) {
753 >            if (t.getState() != Thread.State.TERMINATED) {
754                  t.interrupt();
755                  fail("Test timed out");
756              }
# Line 767 | Line 828 | public class JSR166TestCase extends Test
828                  realRun();
829                  threadShouldThrow("InterruptedException");
830              } catch (InterruptedException success) {
831 +                threadAssertFalse(Thread.interrupted());
832              } catch (Throwable t) {
833                  threadUnexpectedException(t);
834              }
# Line 796 | Line 858 | public class JSR166TestCase extends Test
858                  threadShouldThrow("InterruptedException");
859                  return result;
860              } catch (InterruptedException success) {
861 +                threadAssertFalse(Thread.interrupted());
862              } catch (Throwable t) {
863                  threadUnexpectedException(t);
864              }
# Line 830 | Line 893 | public class JSR166TestCase extends Test
893      public Runnable awaiter(final CountDownLatch latch) {
894          return new CheckedRunnable() {
895              public void realRun() throws InterruptedException {
896 <                latch.await();
896 >                await(latch);
897              }};
898      }
899  
900 +    public void await(CountDownLatch latch) {
901 +        try {
902 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
903 +        } catch (Throwable t) {
904 +            threadUnexpectedException(t);
905 +        }
906 +    }
907 +
908 + //     /**
909 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
910 + //      */
911 + //     public void await(AtomicBoolean flag) {
912 + //         await(flag, LONG_DELAY_MS);
913 + //     }
914 +
915 + //     /**
916 + //      * Spin-waits up to the specified timeout until flag becomes true.
917 + //      */
918 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
919 + //         long startTime = System.nanoTime();
920 + //         while (!flag.get()) {
921 + //             if (millisElapsedSince(startTime) > timeoutMillis)
922 + //                 throw new AssertionFailedError("timed out");
923 + //             Thread.yield();
924 + //         }
925 + //     }
926 +
927      public static class NPETask implements Callable<String> {
928          public String call() { throw new NullPointerException(); }
929      }
# Line 1036 | Line 1126 | public class JSR166TestCase extends Test
1126      }
1127  
1128      /**
1129 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1130 <     * of throwing checked exceptions.
1129 >     * A CyclicBarrier that uses timed await and fails with
1130 >     * AssertionFailedErrors instead of throwing checked exceptions.
1131       */
1132      public class CheckedBarrier extends CyclicBarrier {
1133          public CheckedBarrier(int parties) { super(parties); }
1134  
1135          public int await() {
1136              try {
1137 <                return super.await();
1137 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1138 >            } catch (TimeoutException e) {
1139 >                throw new AssertionFailedError("timed out");
1140              } catch (Exception e) {
1141                  AssertionFailedError afe =
1142                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1054 | Line 1146 | public class JSR166TestCase extends Test
1146          }
1147      }
1148  
1149 <    public void checkEmpty(BlockingQueue q) {
1149 >    void checkEmpty(BlockingQueue q) {
1150          try {
1151              assertTrue(q.isEmpty());
1152              assertEquals(0, q.size());
# Line 1081 | Line 1173 | public class JSR166TestCase extends Test
1173          }
1174      }
1175  
1176 +    @SuppressWarnings("unchecked")
1177 +    <T> T serialClone(T o) {
1178 +        try {
1179 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1180 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1181 +            oos.writeObject(o);
1182 +            oos.flush();
1183 +            oos.close();
1184 +            ObjectInputStream ois = new ObjectInputStream
1185 +                (new ByteArrayInputStream(bos.toByteArray()));
1186 +            T clone = (T) ois.readObject();
1187 +            assertSame(o.getClass(), clone.getClass());
1188 +            return clone;
1189 +        } catch (Throwable t) {
1190 +            threadUnexpectedException(t);
1191 +            return null;
1192 +        }
1193 +    }
1194   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines