/** compareAndSet in one thread enables another waiting for value to succeed */
  public void testCompareAndSetInMultipleThreads() throws Exception {
    x = one;
    final AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer> a;
    try {
      a =
          AtomicReferenceFieldUpdater.newUpdater(
              AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
    } catch (RuntimeException ok) {
      return;
    }

    Thread t =
        new Thread(
            new CheckedRunnable() {
              public void realRun() {
                while (!a.compareAndSet(AtomicReferenceFieldUpdaterTest.this, two, three))
                  Thread.yield();
              }
            });

    t.start();
    assertTrue(a.compareAndSet(this, one, two));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
    assertSame(a.get(this), three);
  }
 /** Checks that the threads do not terminate within the given millisecond delay. */
 void assertThreadsStayAlive(long millis, Thread... threads) {
   try {
     // No need to optimize the failing case via Thread.join.
     delay(millis);
     for (Thread thread : threads) assertTrue(thread.isAlive());
   } catch (InterruptedException ie) {
     fail("Unexpected InterruptedException");
   }
 }
 /** Spin-waits until sync.isQueued(t) becomes true. */
 void waitForQueuedThread(AbstractQueuedLongSynchronizer sync, Thread t) {
   long startTime = System.nanoTime();
   while (!sync.isQueued(t)) {
     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
       throw new AssertionFailedError("timed out");
     Thread.yield();
   }
   assertTrue(t.isAlive());
 }
 /**
  * Spin-waits up to the specified number of milliseconds for the given thread to enter a wait
  * state: BLOCKED, WAITING, or TIMED_WAITING.
  */
 void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
   long startTime = System.nanoTime();
   for (; ; ) {
     Thread.State s = thread.getState();
     if (s == Thread.State.BLOCKED || s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING)
       return;
     else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination");
     else if (millisElapsedSince(startTime) > timeoutMillis) {
       threadAssertTrue(thread.isAlive());
       return;
     }
     Thread.yield();
   }
 }
 /** compareAndSet in one thread enables another waiting for value to succeed */
 public void testCompareAndSetInMultipleThreads() {
   final AtomicLong ai = new AtomicLong(1);
   Thread t =
       new Thread(
           new Runnable() {
             public void run() {
               while (!ai.compareAndSet(2, 3)) Thread.yield();
             }
           });
   try {
     t.start();
     assertTrue(ai.compareAndSet(1, 2));
     t.join(LONG_DELAY_MS);
     assertFalse(t.isAlive());
     assertEquals(ai.get(), 3);
   } catch (Exception e) {
     unexpectedException();
   }
 }