ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ReentrantLockTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ReentrantLockTest.java (file contents):
Revision 1.47 by jsr166, Sun May 15 17:30:21 2011 UTC vs.
Revision 1.67 by jsr166, Fri Sep 29 22:31:55 2017 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.concurrent.locks.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
13 import java.util.*;
14 import java.io.*;
10  
11 + import java.util.ArrayList;
12 + import java.util.Arrays;
13 + import java.util.Collection;
14 + import java.util.HashSet;
15 + import java.util.concurrent.CountDownLatch;
16 + import java.util.concurrent.CyclicBarrier;
17 + import java.util.concurrent.ThreadLocalRandom;
18 + import java.util.concurrent.locks.Condition;
19 + import java.util.concurrent.locks.ReentrantLock;
20 +
21 + import junit.framework.AssertionFailedError;
22 + import junit.framework.Test;
23 + import junit.framework.TestSuite;
24 +
25 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
26   public class ReentrantLockTest extends JSR166TestCase {
27      public static void main(String[] args) {
28 <        junit.textui.TestRunner.run(suite());
28 >        main(suite(), args);
29      }
30      public static Test suite() {
31          return new TestSuite(ReentrantLockTest.class);
32      }
33  
34      /**
35 <     * A runnable calling lockInterruptibly
35 >     * A checked runnable calling lockInterruptibly
36       */
37      class InterruptibleLockRunnable extends CheckedRunnable {
38          final ReentrantLock lock;
39 <        InterruptibleLockRunnable(ReentrantLock l) { lock = l; }
39 >        InterruptibleLockRunnable(ReentrantLock lock) { this.lock = lock; }
40          public void realRun() throws InterruptedException {
41              lock.lockInterruptibly();
42          }
43      }
44  
45      /**
46 <     * A runnable calling lockInterruptibly that expects to be
46 >     * A checked runnable calling lockInterruptibly that expects to be
47       * interrupted
48       */
49      class InterruptedLockRunnable extends CheckedInterruptedRunnable {
50          final ReentrantLock lock;
51 <        InterruptedLockRunnable(ReentrantLock l) { lock = l; }
51 >        InterruptedLockRunnable(ReentrantLock lock) { this.lock = lock; }
52          public void realRun() throws InterruptedException {
53              lock.lockInterruptibly();
54          }
# Line 82 | Line 92 | public class ReentrantLockTest extends J
92              Thread.yield();
93          }
94          assertTrue(t.isAlive());
95 <        assertTrue(lock.getOwner() != t);
95 >        assertNotSame(t, lock.getOwner());
96      }
97  
98      /**
# Line 136 | Line 146 | public class ReentrantLockTest extends J
146          lock.unlock();
147      }
148  
149 <    enum AwaitMethod { await, awaitNanos, awaitUntil };
149 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
150 >
151 >    static AwaitMethod randomAwaitMethod() {
152 >        AwaitMethod[] awaitMethods = AwaitMethod.values();
153 >        return awaitMethods[ThreadLocalRandom.current().nextInt(awaitMethods.length)];
154 >    }
155  
156      /**
157 <     * Awaits condition using the specified AwaitMethod.
157 >     * Awaits condition "indefinitely" using the specified AwaitMethod.
158       */
159      void await(Condition c, AwaitMethod awaitMethod)
160              throws InterruptedException {
161 +        long timeoutMillis = 2 * LONG_DELAY_MS;
162          switch (awaitMethod) {
163          case await:
164              c.await();
165              break;
166 +        case awaitTimed:
167 +            assertTrue(c.await(timeoutMillis, MILLISECONDS));
168 +            break;
169          case awaitNanos:
170 <            long nanosRemaining = c.awaitNanos(MILLISECONDS.toNanos(2 * LONG_DELAY_MS));
171 <            assertTrue(nanosRemaining > 0);
170 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
171 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
172 >            assertTrue(nanosRemaining > timeoutNanos / 2);
173 >            assertTrue(nanosRemaining <= timeoutNanos);
174              break;
175          case awaitUntil:
176 <            java.util.Date d = new java.util.Date();
156 <            assertTrue(c.awaitUntil(new java.util.Date(d.getTime() + 2 * LONG_DELAY_MS)));
176 >            assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
177              break;
178 +        default:
179 +            throw new AssertionError();
180          }
181      }
182  
# Line 195 | Line 217 | public class ReentrantLockTest extends J
217      public void testUnlock_IMSE()      { testUnlock_IMSE(false); }
218      public void testUnlock_IMSE_fair() { testUnlock_IMSE(true); }
219      public void testUnlock_IMSE(boolean fair) {
220 <        ReentrantLock lock = new ReentrantLock(fair);
220 >        final ReentrantLock lock = new ReentrantLock(fair);
221          try {
222              lock.unlock();
223              shouldThrow();
# Line 282 | Line 304 | public class ReentrantLockTest extends J
304      }
305  
306      /**
307 <     * hasQueuedThread reports whether a thread is queued.
307 >     * hasQueuedThread reports whether a thread is queued
308       */
309      public void testHasQueuedThread()      { testHasQueuedThread(false); }
310      public void testHasQueuedThread_fair() { testHasQueuedThread(true); }
# Line 343 | Line 365 | public class ReentrantLockTest extends J
365      }
366  
367      /**
368 <     * timed tryLock is interruptible.
368 >     * timed tryLock is interruptible
369       */
370      public void testTryLock_Interruptible()      { testTryLock_Interruptible(false); }
371      public void testTryLock_Interruptible_fair() { testTryLock_Interruptible(true); }
# Line 385 | Line 407 | public class ReentrantLockTest extends J
407      public void testTryLock_Timeout_fair() { testTryLock_Timeout(true); }
408      public void testTryLock_Timeout(boolean fair) {
409          final PublicReentrantLock lock = new PublicReentrantLock(fair);
410 +        final long timeoutMillis = timeoutMillis();
411          lock.lock();
412          Thread t = newStartedThread(new CheckedRunnable() {
413              public void realRun() throws InterruptedException {
414                  long startTime = System.nanoTime();
392                long timeoutMillis = 10;
415                  assertFalse(lock.tryLock(timeoutMillis, MILLISECONDS));
416                  assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
417              }});
# Line 404 | Line 426 | public class ReentrantLockTest extends J
426      public void testGetHoldCount()      { testGetHoldCount(false); }
427      public void testGetHoldCount_fair() { testGetHoldCount(true); }
428      public void testGetHoldCount(boolean fair) {
429 <        ReentrantLock lock = new ReentrantLock(fair);
429 >        final ReentrantLock lock = new ReentrantLock(fair);
430          for (int i = 1; i <= SIZE; i++) {
431              lock.lock();
432              assertEquals(i, lock.getHoldCount());
433          }
434          for (int i = SIZE; i > 0; i--) {
435              lock.unlock();
436 <            assertEquals(i-1, lock.getHoldCount());
436 >            assertEquals(i - 1, lock.getHoldCount());
437          }
438      }
439  
# Line 421 | Line 443 | public class ReentrantLockTest extends J
443      public void testIsLocked()      { testIsLocked(false); }
444      public void testIsLocked_fair() { testIsLocked(true); }
445      public void testIsLocked(boolean fair) {
446 +        final ReentrantLock lock = new ReentrantLock(fair);
447          try {
425            final ReentrantLock lock = new ReentrantLock(fair);
448              assertFalse(lock.isLocked());
449              lock.lock();
450              assertTrue(lock.isLocked());
# Line 447 | Line 469 | public class ReentrantLockTest extends J
469              barrier.await();
470              awaitTermination(t);
471              assertFalse(lock.isLocked());
472 <        } catch (Exception e) {
451 <            threadUnexpectedException(e);
452 <        }
472 >        } catch (Exception fail) { threadUnexpectedException(fail); }
473      }
474  
475      /**
# Line 461 | Line 481 | public class ReentrantLockTest extends J
481          final PublicReentrantLock lock = new PublicReentrantLock(fair);
482          try {
483              lock.lockInterruptibly();
484 <        } catch (InterruptedException ie) {
465 <            threadUnexpectedException(ie);
466 <        }
484 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
485          assertLockedByMoi(lock);
486          Thread t = newStartedThread(new InterruptedLockRunnable(lock));
487          waitForQueuedThread(lock, t);
# Line 482 | Line 500 | public class ReentrantLockTest extends J
500      public void testAwait_IMSE(boolean fair) {
501          final ReentrantLock lock = new ReentrantLock(fair);
502          final Condition c = lock.newCondition();
503 <        long startTime = System.nanoTime();
504 <        try {
487 <            try {
488 <                c.await();
489 <                shouldThrow();
490 <            } catch (IllegalMonitorStateException success) {}
491 <            try {
492 <                c.await(LONG_DELAY_MS, MILLISECONDS);
493 <                shouldThrow();
494 <            } catch (IllegalMonitorStateException success) {}
495 <            try {
496 <                c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
497 <                shouldThrow();
498 <            } catch (IllegalMonitorStateException success) {}
503 >        for (AwaitMethod awaitMethod : AwaitMethod.values()) {
504 >            long startTime = System.nanoTime();
505              try {
506 <                c.awaitUninterruptibly();
506 >                await(c, awaitMethod);
507                  shouldThrow();
508 <            } catch (IllegalMonitorStateException success) {}
509 <        } catch (InterruptedException ie) {
510 <            threadUnexpectedException(ie);
508 >            } catch (IllegalMonitorStateException success) {
509 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
510 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
511          }
506        assertTrue(millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
512      }
513  
514      /**
# Line 526 | Line 531 | public class ReentrantLockTest extends J
531      public void testAwaitNanos_Timeout()      { testAwaitNanos_Timeout(false); }
532      public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); }
533      public void testAwaitNanos_Timeout(boolean fair) {
534 +        final ReentrantLock lock = new ReentrantLock(fair);
535 +        final Condition c = lock.newCondition();
536 +        final long timeoutMillis = timeoutMillis();
537 +        final long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
538 +        lock.lock();
539 +        final long startTime = System.nanoTime();
540          try {
530            final ReentrantLock lock = new ReentrantLock(fair);
531            final Condition c = lock.newCondition();
532            lock.lock();
533            long startTime = System.nanoTime();
534            long timeoutMillis = 10;
535            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
541              long nanosRemaining = c.awaitNanos(timeoutNanos);
542              assertTrue(nanosRemaining <= 0);
543 <            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
544 <            lock.unlock();
545 <        } catch (InterruptedException e) {
541 <            threadUnexpectedException(e);
542 <        }
543 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
544 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
545 >        lock.unlock();
546      }
547  
548      /**
# Line 548 | Line 551 | public class ReentrantLockTest extends J
551      public void testAwait_Timeout()      { testAwait_Timeout(false); }
552      public void testAwait_Timeout_fair() { testAwait_Timeout(true); }
553      public void testAwait_Timeout(boolean fair) {
554 +        final ReentrantLock lock = new ReentrantLock(fair);
555 +        final Condition c = lock.newCondition();
556 +        final long timeoutMillis = timeoutMillis();
557 +        lock.lock();
558 +        final long startTime = System.nanoTime();
559          try {
552            final ReentrantLock lock = new ReentrantLock(fair);
553            final Condition c = lock.newCondition();
554            lock.lock();
555            long startTime = System.nanoTime();
556            long timeoutMillis = 10;
560              assertFalse(c.await(timeoutMillis, MILLISECONDS));
561 <            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
562 <            lock.unlock();
563 <        } catch (InterruptedException e) {
561 <            threadUnexpectedException(e);
562 <        }
561 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
562 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
563 >        lock.unlock();
564      }
565  
566      /**
# Line 568 | Line 569 | public class ReentrantLockTest extends J
569      public void testAwaitUntil_Timeout()      { testAwaitUntil_Timeout(false); }
570      public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); }
571      public void testAwaitUntil_Timeout(boolean fair) {
572 +        final ReentrantLock lock = new ReentrantLock(fair);
573 +        final Condition c = lock.newCondition();
574 +        lock.lock();
575 +        // We shouldn't assume that nanoTime and currentTimeMillis
576 +        // use the same time source, so don't use nanoTime here.
577 +        final java.util.Date delayedDate = delayedDate(timeoutMillis());
578          try {
579 <            final ReentrantLock lock = new ReentrantLock(fair);
580 <            final Condition c = lock.newCondition();
581 <            lock.lock();
582 <            long startTime = System.nanoTime();
576 <            long timeoutMillis = 10;
577 <            java.util.Date d = new java.util.Date();
578 <            assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + timeoutMillis)));
579 <            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
580 <            lock.unlock();
581 <        } catch (InterruptedException e) {
582 <            threadUnexpectedException(e);
583 <        }
579 >            assertFalse(c.awaitUntil(delayedDate));
580 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
581 >        assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
582 >        lock.unlock();
583      }
584  
585      /**
# Line 744 | Line 743 | public class ReentrantLockTest extends J
743      public void testHasWaiters(boolean fair) {
744          final PublicReentrantLock lock = new PublicReentrantLock(fair);
745          final Condition c = lock.newCondition();
746 <        final CountDownLatch locked = new CountDownLatch(1);
746 >        final CountDownLatch pleaseSignal = new CountDownLatch(1);
747          Thread t = newStartedThread(new CheckedRunnable() {
748              public void realRun() throws InterruptedException {
749                  lock.lock();
750                  assertHasNoWaiters(lock, c);
751                  assertFalse(lock.hasWaiters(c));
752 <                locked.countDown();
752 >                pleaseSignal.countDown();
753                  c.await();
754                  assertHasNoWaiters(lock, c);
755                  assertFalse(lock.hasWaiters(c));
756                  lock.unlock();
757              }});
758  
759 <        await(locked);
759 >        await(pleaseSignal);
760          lock.lock();
761          assertHasWaiters(lock, c, t);
762          assertTrue(lock.hasWaiters(c));
# Line 888 | Line 887 | public class ReentrantLockTest extends J
887      }
888  
889      /**
890 <     * awaitUninterruptibly doesn't abort on interrupt
890 >     * awaitUninterruptibly is uninterruptible
891       */
892      public void testAwaitUninterruptibly()      { testAwaitUninterruptibly(false); }
893      public void testAwaitUninterruptibly_fair() { testAwaitUninterruptibly(true); }
894      public void testAwaitUninterruptibly(boolean fair) {
895          final ReentrantLock lock = new ReentrantLock(fair);
896 <        final Condition c = lock.newCondition();
897 <        final CountDownLatch locked = new CountDownLatch(1);
898 <        Thread t = newStartedThread(new CheckedRunnable() {
896 >        final Condition condition = lock.newCondition();
897 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
898 >
899 >        Thread t1 = newStartedThread(new CheckedRunnable() {
900              public void realRun() {
901 +                // Interrupt before awaitUninterruptibly
902                  lock.lock();
903 <                locked.countDown();
904 <                c.awaitUninterruptibly();
903 >                pleaseInterrupt.countDown();
904 >                Thread.currentThread().interrupt();
905 >                condition.awaitUninterruptibly();
906                  assertTrue(Thread.interrupted());
907                  lock.unlock();
908              }});
909  
910 <        await(locked);
910 >        Thread t2 = newStartedThread(new CheckedRunnable() {
911 >            public void realRun() {
912 >                // Interrupt during awaitUninterruptibly
913 >                lock.lock();
914 >                pleaseInterrupt.countDown();
915 >                condition.awaitUninterruptibly();
916 >                assertTrue(Thread.interrupted());
917 >                lock.unlock();
918 >            }});
919 >
920 >        await(pleaseInterrupt);
921 >        t2.interrupt();
922          lock.lock();
923          lock.unlock();
924 <        t.interrupt();
925 <        long timeoutMillis = 10;
926 <        assertThreadStaysAlive(t, timeoutMillis);
924 >        assertThreadBlocks(t1, Thread.State.WAITING);
925 >        assertThreadBlocks(t2, Thread.State.WAITING);
926 >
927          lock.lock();
928 <        c.signal();
928 >        condition.signalAll();
929          lock.unlock();
930 <        awaitTermination(t);
930 >
931 >        awaitTermination(t1);
932 >        awaitTermination(t2);
933      }
934  
935      /**
# Line 922 | Line 937 | public class ReentrantLockTest extends J
937       */
938      public void testInterruptible_await()           { testInterruptible(false, AwaitMethod.await); }
939      public void testInterruptible_await_fair()      { testInterruptible(true,  AwaitMethod.await); }
940 +    public void testInterruptible_awaitTimed()      { testInterruptible(false, AwaitMethod.awaitTimed); }
941 +    public void testInterruptible_awaitTimed_fair() { testInterruptible(true,  AwaitMethod.awaitTimed); }
942      public void testInterruptible_awaitNanos()      { testInterruptible(false, AwaitMethod.awaitNanos); }
943      public void testInterruptible_awaitNanos_fair() { testInterruptible(true,  AwaitMethod.awaitNanos); }
944      public void testInterruptible_awaitUntil()      { testInterruptible(false, AwaitMethod.awaitUntil); }
# Line 930 | Line 947 | public class ReentrantLockTest extends J
947          final PublicReentrantLock lock =
948              new PublicReentrantLock(fair);
949          final Condition c = lock.newCondition();
950 <        final CountDownLatch locked = new CountDownLatch(1);
950 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
951          Thread t = newStartedThread(new CheckedInterruptedRunnable() {
952              public void realRun() throws InterruptedException {
953                  lock.lock();
954                  assertLockedByMoi(lock);
955                  assertHasNoWaiters(lock, c);
956 <                locked.countDown();
956 >                pleaseInterrupt.countDown();
957                  try {
958                      await(c, awaitMethod);
959                  } finally {
# Line 947 | Line 964 | public class ReentrantLockTest extends J
964                  }
965              }});
966  
967 <        await(locked);
967 >        await(pleaseInterrupt);
968          assertHasWaiters(lock, c, t);
969          t.interrupt();
970          awaitTermination(t);
# Line 959 | Line 976 | public class ReentrantLockTest extends J
976       */
977      public void testSignalAll_await()           { testSignalAll(false, AwaitMethod.await); }
978      public void testSignalAll_await_fair()      { testSignalAll(true,  AwaitMethod.await); }
979 +    public void testSignalAll_awaitTimed()      { testSignalAll(false, AwaitMethod.awaitTimed); }
980 +    public void testSignalAll_awaitTimed_fair() { testSignalAll(true,  AwaitMethod.awaitTimed); }
981      public void testSignalAll_awaitNanos()      { testSignalAll(false, AwaitMethod.awaitNanos); }
982      public void testSignalAll_awaitNanos_fair() { testSignalAll(true,  AwaitMethod.awaitNanos); }
983      public void testSignalAll_awaitUntil()      { testSignalAll(false, AwaitMethod.awaitUntil); }
# Line 966 | Line 985 | public class ReentrantLockTest extends J
985      public void testSignalAll(boolean fair, final AwaitMethod awaitMethod) {
986          final PublicReentrantLock lock = new PublicReentrantLock(fair);
987          final Condition c = lock.newCondition();
988 <        final CountDownLatch locked = new CountDownLatch(2);
988 >        final CountDownLatch pleaseSignal = new CountDownLatch(2);
989          class Awaiter extends CheckedRunnable {
990              public void realRun() throws InterruptedException {
991                  lock.lock();
992 <                locked.countDown();
992 >                pleaseSignal.countDown();
993                  await(c, awaitMethod);
994                  lock.unlock();
995              }
# Line 979 | Line 998 | public class ReentrantLockTest extends J
998          Thread t1 = newStartedThread(new Awaiter());
999          Thread t2 = newStartedThread(new Awaiter());
1000  
1001 <        await(locked);
1001 >        await(pleaseSignal);
1002          lock.lock();
1003          assertHasWaiters(lock, c, t1, t2);
1004          c.signalAll();
# Line 990 | Line 1009 | public class ReentrantLockTest extends J
1009      }
1010  
1011      /**
1012 <     * signal wakes up waiting threads in FIFO order.
1012 >     * signal wakes up waiting threads in FIFO order
1013       */
1014      public void testSignalWakesFifo()      { testSignalWakesFifo(false); }
1015      public void testSignalWakesFifo_fair() { testSignalWakesFifo(true); }
# Line 1044 | Line 1063 | public class ReentrantLockTest extends J
1063      public void testAwaitLockCount(boolean fair) {
1064          final PublicReentrantLock lock = new PublicReentrantLock(fair);
1065          final Condition c = lock.newCondition();
1066 <        final CountDownLatch locked = new CountDownLatch(2);
1066 >        final CountDownLatch pleaseSignal = new CountDownLatch(2);
1067          Thread t1 = newStartedThread(new CheckedRunnable() {
1068              public void realRun() throws InterruptedException {
1069                  lock.lock();
1070                  assertLockedByMoi(lock);
1071                  assertEquals(1, lock.getHoldCount());
1072 <                locked.countDown();
1072 >                pleaseSignal.countDown();
1073                  c.await();
1074                  assertLockedByMoi(lock);
1075                  assertEquals(1, lock.getHoldCount());
# Line 1063 | Line 1082 | public class ReentrantLockTest extends J
1082                  lock.lock();
1083                  assertLockedByMoi(lock);
1084                  assertEquals(2, lock.getHoldCount());
1085 <                locked.countDown();
1085 >                pleaseSignal.countDown();
1086                  c.await();
1087                  assertLockedByMoi(lock);
1088                  assertEquals(2, lock.getHoldCount());
# Line 1071 | Line 1090 | public class ReentrantLockTest extends J
1090                  lock.unlock();
1091              }});
1092  
1093 <        await(locked);
1093 >        await(pleaseSignal);
1094          lock.lock();
1095          assertHasWaiters(lock, c, t1, t2);
1096          assertEquals(1, lock.getHoldCount());
# Line 1088 | Line 1107 | public class ReentrantLockTest extends J
1107      public void testSerialization()      { testSerialization(false); }
1108      public void testSerialization_fair() { testSerialization(true); }
1109      public void testSerialization(boolean fair) {
1110 <        ReentrantLock lock = new ReentrantLock(fair);
1110 >        final ReentrantLock lock = new ReentrantLock(fair);
1111          lock.lock();
1112  
1113          ReentrantLock clone = serialClone(lock);
# Line 1114 | Line 1133 | public class ReentrantLockTest extends J
1133      public void testToString()      { testToString(false); }
1134      public void testToString_fair() { testToString(true); }
1135      public void testToString(boolean fair) {
1136 <        ReentrantLock lock = new ReentrantLock(fair);
1137 <        String us = lock.toString();
1119 <        assertTrue(us.indexOf("Unlocked") >= 0);
1136 >        final ReentrantLock lock = new ReentrantLock(fair);
1137 >        assertTrue(lock.toString().contains("Unlocked"));
1138          lock.lock();
1139 <        String ls = lock.toString();
1140 <        assertTrue(ls.indexOf("Locked") >= 0);
1139 >        assertTrue(lock.toString().contains("Locked by"));
1140 >        lock.unlock();
1141 >        assertTrue(lock.toString().contains("Unlocked"));
1142 >    }
1143 >
1144 >    /**
1145 >     * Tests scenario for JDK-8187408
1146 >     * AbstractQueuedSynchronizer wait queue corrupted when thread awaits without holding the lock
1147 >     */
1148 >    public void testBug8187408() throws InterruptedException {
1149 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1150 >        final AwaitMethod awaitMethod = randomAwaitMethod();
1151 >        final int nThreads = rnd.nextInt(2, 10);
1152 >        final ReentrantLock lock = new ReentrantLock();
1153 >        final Condition cond = lock.newCondition();
1154 >        final CountDownLatch done = new CountDownLatch(nThreads);
1155 >        final ArrayList<Thread> threads = new ArrayList<>();
1156 >
1157 >        Runnable rogue = () -> {
1158 >            while (done.getCount() > 0) {
1159 >                try {
1160 >                    // call await without holding lock?!
1161 >                    await(cond, awaitMethod);
1162 >                    throw new AssertionError("should throw");
1163 >                }
1164 >                catch (IllegalMonitorStateException expected) {}
1165 >                catch (Throwable fail) { threadUnexpectedException(fail); }}};
1166 >        Thread rogueThread = new Thread(rogue, "rogue");
1167 >        threads.add(rogueThread);
1168 >        rogueThread.start();
1169 >
1170 >        Runnable waiter = () -> {
1171 >            lock.lock();
1172 >            try {
1173 >                done.countDown();
1174 >                cond.await();
1175 >            } catch (Throwable fail) {
1176 >                threadUnexpectedException(fail);
1177 >            } finally {
1178 >                lock.unlock();
1179 >            }};
1180 >        for (int i = 0; i < nThreads; i++) {
1181 >            Thread thread = new Thread(waiter, "waiter");
1182 >            threads.add(thread);
1183 >            thread.start();
1184 >        }
1185 >
1186 >        assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1187 >        lock.lock();
1188 >        try {
1189 >            assertEquals(nThreads, lock.getWaitQueueLength(cond));
1190 >        } finally {
1191 >            cond.signalAll();
1192 >            lock.unlock();
1193 >        }
1194 >        for (Thread thread : threads) {
1195 >            thread.join(LONG_DELAY_MS);
1196 >            assertFalse(thread.isAlive());
1197 >        }
1198      }
1199   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines