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

Comparing jsr166/src/test/tck/AbstractQueuedSynchronizerTest.java (file contents):
Revision 1.47 by jsr166, Wed Dec 31 19:05:42 2014 UTC vs.
Revision 1.62 by dl, Sun Jan 7 23:05:44 2018 UTC

# Line 9 | Line 9
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10   import static java.util.concurrent.TimeUnit.NANOSECONDS;
11  
12 + import java.util.ArrayList;
13   import java.util.Arrays;
14   import java.util.Collection;
15   import java.util.HashSet;
16 + import java.util.concurrent.ThreadLocalRandom;
17   import java.util.concurrent.locks.AbstractQueuedSynchronizer;
18   import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject;
19  
# Line 19 | Line 21 | import junit.framework.AssertionFailedEr
21   import junit.framework.Test;
22   import junit.framework.TestSuite;
23  
24 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
25   public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
26      public static void main(String[] args) {
27 <        junit.textui.TestRunner.run(suite());
27 >        main(suite(), args);
28      }
29      public static Test suite() {
30          return new TestSuite(AbstractQueuedSynchronizerTest.class);
# Line 33 | Line 36 | public class AbstractQueuedSynchronizerT
36       * methods/features of AbstractQueuedSynchronizer are tested via
37       * other test classes, including those for ReentrantLock,
38       * ReentrantReadWriteLock, and Semaphore.
39 +     *
40 +     * Unlike the javadoc sample, we don't track owner thread via
41 +     * AbstractOwnableSynchronizer methods.
42       */
43      static class Mutex extends AbstractQueuedSynchronizer {
44          /** An eccentric value for locked synchronizer state. */
# Line 40 | Line 46 | public class AbstractQueuedSynchronizerT
46  
47          static final int UNLOCKED = 0;
48  
49 +        /** Owner thread is untracked, so this is really just isLocked(). */
50          @Override public boolean isHeldExclusively() {
51              int state = getState();
52              assertTrue(state == UNLOCKED || state == LOCKED);
53              return state == LOCKED;
54          }
55  
56 <        @Override public boolean tryAcquire(int acquires) {
56 >        @Override protected boolean tryAcquire(int acquires) {
57              assertEquals(LOCKED, acquires);
58              return compareAndSetState(UNLOCKED, LOCKED);
59          }
60  
61 <        @Override public boolean tryRelease(int releases) {
61 >        @Override protected boolean tryRelease(int releases) {
62              if (getState() != LOCKED) throw new IllegalMonitorStateException();
63              assertEquals(LOCKED, releases);
64              setState(UNLOCKED);
# Line 82 | Line 89 | public class AbstractQueuedSynchronizerT
89              release(LOCKED);
90          }
91  
92 +        /** Faux-Implements Lock.newCondition(). */
93          public ConditionObject newCondition() {
94              return new ConditionObject();
95          }
96      }
97  
98      /**
99 <     * A simple latch class, to test shared mode.
99 >     * A minimal latch class, to test shared mode.
100       */
101      static class BooleanLatch extends AbstractQueuedSynchronizer {
102          public boolean isSignalled() { return getState() != 0; }
# Line 228 | Line 236 | public class AbstractQueuedSynchronizerT
236          case awaitUntil:
237              assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
238              break;
239 +        default:
240 +            throw new AssertionError();
241          }
242      }
243  
# Line 236 | Line 246 | public class AbstractQueuedSynchronizerT
246       * default timeout duration).
247       */
248      void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
249 <        long timeoutMillis = timeoutMillis();
250 <        long startTime = System.nanoTime();
249 >        final long timeoutMillis = timeoutMillis();
250 >        final long startTime;
251          try {
252              switch (awaitMethod) {
253              case awaitTimed:
254 +                startTime = System.nanoTime();
255                  assertFalse(c.await(timeoutMillis, MILLISECONDS));
256 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
257                  break;
258              case awaitNanos:
259 +                startTime = System.nanoTime();
260                  long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
261                  long nanosRemaining = c.awaitNanos(nanosTimeout);
262                  assertTrue(nanosRemaining <= 0);
263 +                assertTrue(nanosRemaining > -MILLISECONDS.toNanos(LONG_DELAY_MS));
264 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
265                  break;
266              case awaitUntil:
267 +                // We shouldn't assume that nanoTime and currentTimeMillis
268 +                // use the same time source, so don't use nanoTime here.
269 +                java.util.Date delayedDate = delayedDate(timeoutMillis);
270                  assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
271 +                assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
272                  break;
273              default:
274                  throw new UnsupportedOperationException();
275              }
276          } catch (InterruptedException ie) { threadUnexpectedException(ie); }
258        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
277      }
278  
279      /**
# Line 958 | Line 976 | public class AbstractQueuedSynchronizerT
976       */
977      public void testAwaitUninterruptibly() {
978          final Mutex sync = new Mutex();
979 <        final ConditionObject c = sync.newCondition();
979 >        final ConditionObject condition = sync.newCondition();
980          final BooleanLatch pleaseInterrupt = new BooleanLatch();
981          Thread t = newStartedThread(new CheckedRunnable() {
982              public void realRun() {
983                  sync.acquire();
984                  assertTrue(pleaseInterrupt.releaseShared(0));
985 <                c.awaitUninterruptibly();
985 >                condition.awaitUninterruptibly();
986                  assertTrue(Thread.interrupted());
987 <                assertHasWaitersLocked(sync, c, NO_THREADS);
987 >                assertHasWaitersLocked(sync, condition, NO_THREADS);
988                  sync.release();
989              }});
990  
991          pleaseInterrupt.acquireShared(0);
992          sync.acquire();
993 <        assertHasWaitersLocked(sync, c, t);
993 >        assertHasWaitersLocked(sync, condition, t);
994          sync.release();
995          t.interrupt();
996 <        assertHasWaitersUnlocked(sync, c, t);
997 <        assertThreadStaysAlive(t);
996 >        assertHasWaitersUnlocked(sync, condition, t);
997 >        assertThreadBlocks(t, Thread.State.WAITING);
998          sync.acquire();
999 <        assertHasWaitersLocked(sync, c, t);
999 >        assertHasWaitersLocked(sync, condition, t);
1000          assertHasExclusiveQueuedThreads(sync, NO_THREADS);
1001 <        c.signal();
1002 <        assertHasWaitersLocked(sync, c, NO_THREADS);
1001 >        condition.signal();
1002 >        assertHasWaitersLocked(sync, condition, NO_THREADS);
1003          assertHasExclusiveQueuedThreads(sync, t);
1004          sync.release();
1005          awaitTermination(t);
# Line 1124 | Line 1142 | public class AbstractQueuedSynchronizerT
1142  
1143          waitForQueuedThread(l, t);
1144          assertFalse(l.isSignalled());
1145 <        assertThreadStaysAlive(t);
1145 >        assertThreadBlocks(t, Thread.State.WAITING);
1146          assertHasSharedQueuedThreads(l, t);
1147          assertTrue(l.releaseShared(0));
1148          assertTrue(l.isSignalled());
# Line 1149 | Line 1167 | public class AbstractQueuedSynchronizerT
1167  
1168          waitForQueuedThread(l, t);
1169          assertFalse(l.isSignalled());
1170 <        assertThreadStaysAlive(t);
1170 >        assertThreadBlocks(t, Thread.State.TIMED_WAITING);
1171          assertTrue(l.releaseShared(0));
1172          assertTrue(l.isSignalled());
1173          awaitTermination(t);
# Line 1198 | Line 1216 | public class AbstractQueuedSynchronizerT
1216      public void testTryAcquireSharedNanos_Timeout() {
1217          final BooleanLatch l = new BooleanLatch();
1218          final BooleanLatch observedQueued = new BooleanLatch();
1201        final long timeoutMillis = timeoutMillis();
1219          Thread t = newStartedThread(new CheckedRunnable() {
1220              public void realRun() throws InterruptedException {
1221                  assertFalse(l.isSignalled());
# Line 1244 | Line 1261 | public class AbstractQueuedSynchronizerT
1261          sync.release();
1262      }
1263  
1264 +    /**
1265 +     * JDK-8191483: AbstractQueuedSynchronizer cancel/cancel race
1266 +     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testCancelCancelRace -Djsr166.runsPerTest=100 tck
1267 +     */
1268 +    public void testCancelCancelRace() throws InterruptedException {
1269 +        class Sync extends AbstractQueuedSynchronizer {
1270 +            protected boolean tryAcquire(int acquires) {
1271 +                return !hasQueuedPredecessors() && compareAndSetState(0, 1);
1272 +            }
1273 +            protected boolean tryRelease(int releases) {
1274 +                return compareAndSetState(1, 0);
1275 +            }
1276 +        }
1277 +
1278 +        Sync s = new Sync();
1279 +        s.acquire(1);           // acquire to force other threads to enqueue
1280 +
1281 +        // try to trigger double cancel race with two background threads
1282 +        ArrayList<Thread> threads = new ArrayList<>();
1283 +        Runnable failedAcquire = () -> {
1284 +            try {
1285 +                s.acquireInterruptibly(1);
1286 +                shouldThrow();
1287 +            } catch (InterruptedException expected) {}
1288 +        };
1289 +        for (int i = 0; i < 2; i++) {
1290 +            Thread thread = new Thread(failedAcquire);
1291 +            thread.start();
1292 +            threads.add(thread);
1293 +        }
1294 +        Thread.sleep(100);
1295 +        for (Thread thread : threads) thread.interrupt();
1296 +        for (Thread thread : threads) awaitTermination(thread);
1297 +
1298 +        s.release(1);
1299 +
1300 +        // no one holds lock now, we should be able to acquire
1301 +        if (!s.tryAcquire(1))
1302 +            throw new RuntimeException(
1303 +                String.format(
1304 +                    "Broken: hasQueuedPredecessors=%s hasQueuedThreads=%s queueLength=%d firstQueuedThread=%s",
1305 +                    s.hasQueuedPredecessors(),
1306 +                    s.hasQueuedThreads(),
1307 +                    s.getQueueLength(),
1308 +                    s.getFirstQueuedThread()));
1309 +    }
1310 +
1311 +    /**
1312 +     * Tests scenario for
1313 +     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1314 +     */
1315 +    public void testInterruptedFailingAcquire() throws InterruptedException {
1316 +        final RuntimeException ex = new RuntimeException();
1317 +
1318 +        // A synchronizer only offering a choice of failure modes
1319 +        class Sync extends AbstractQueuedSynchronizer {
1320 +            boolean pleaseThrow;
1321 +            @Override protected boolean tryAcquire(int ignored) {
1322 +                if (pleaseThrow) throw ex;
1323 +                return false;
1324 +            }
1325 +            @Override protected int tryAcquireShared(int ignored) {
1326 +                if (pleaseThrow) throw ex;
1327 +                return -1;
1328 +            }
1329 +            @Override protected boolean tryRelease(int ignored) {
1330 +                return true;
1331 +            }
1332 +            @Override protected boolean tryReleaseShared(int ignored) {
1333 +                return true;
1334 +            }
1335 +        }
1336 +
1337 +        final Sync s = new Sync();
1338 +
1339 +        final Thread thread = newStartedThread(new CheckedRunnable() {
1340 +            public void realRun() {
1341 +                try {
1342 +                    if (ThreadLocalRandom.current().nextBoolean())
1343 +                        s.acquire(1);
1344 +                    else
1345 +                        s.acquireShared(1);
1346 +                    shouldThrow();
1347 +                } catch (Throwable t) {
1348 +                    assertSame(ex, t);
1349 +                    assertTrue(Thread.interrupted());
1350 +                }
1351 +            }});
1352 +        waitForThreadToEnterWaitState(thread);
1353 +        assertSame(thread, s.getFirstQueuedThread());
1354 +        assertTrue(s.hasQueuedPredecessors());
1355 +        assertTrue(s.hasQueuedThreads());
1356 +        assertEquals(1, s.getQueueLength());
1357 +
1358 +        s.pleaseThrow = true;
1359 +        thread.interrupt();
1360 +        s.release(1);
1361 +        awaitTermination(thread);
1362 +    }
1363 +
1364   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines