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.44 by jsr166, Thu May 2 18:01:09 2013 UTC vs.
Revision 1.73 by jsr166, Fri Aug 16 02:32:26 2019 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
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.atomic.AtomicBoolean;
17   import java.util.concurrent.locks.AbstractQueuedSynchronizer;
18   import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject;
19  
20 + import junit.framework.Test;
21 + import junit.framework.TestSuite;
22 +
23 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
24   public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
25      public static void main(String[] args) {
26 <        junit.textui.TestRunner.run(suite());
26 >        main(suite(), args);
27      }
28      public static Test suite() {
29          return new TestSuite(AbstractQueuedSynchronizerTest.class);
# Line 26 | Line 35 | public class AbstractQueuedSynchronizerT
35       * methods/features of AbstractQueuedSynchronizer are tested via
36       * other test classes, including those for ReentrantLock,
37       * ReentrantReadWriteLock, and Semaphore.
38 +     *
39 +     * Unlike the javadoc sample, we don't track owner thread via
40 +     * AbstractOwnableSynchronizer methods.
41       */
42      static class Mutex extends AbstractQueuedSynchronizer {
43          /** An eccentric value for locked synchronizer state. */
# Line 33 | Line 45 | public class AbstractQueuedSynchronizerT
45  
46          static final int UNLOCKED = 0;
47  
48 +        /** Owner thread is untracked, so this is really just isLocked(). */
49          @Override public boolean isHeldExclusively() {
50              int state = getState();
51              assertTrue(state == UNLOCKED || state == LOCKED);
52              return state == LOCKED;
53          }
54  
55 <        @Override public boolean tryAcquire(int acquires) {
55 >        @Override protected boolean tryAcquire(int acquires) {
56              assertEquals(LOCKED, acquires);
57              return compareAndSetState(UNLOCKED, LOCKED);
58          }
59  
60 <        @Override public boolean tryRelease(int releases) {
60 >        @Override protected boolean tryRelease(int releases) {
61              if (getState() != LOCKED) throw new IllegalMonitorStateException();
62              assertEquals(LOCKED, releases);
63              setState(UNLOCKED);
# Line 75 | Line 88 | public class AbstractQueuedSynchronizerT
88              release(LOCKED);
89          }
90  
91 +        /** Faux-Implements Lock.newCondition(). */
92          public ConditionObject newCondition() {
93              return new ConditionObject();
94          }
95      }
96  
97      /**
98 <     * A simple latch class, to test shared mode.
98 >     * A minimal latch class, to test shared mode.
99       */
100      static class BooleanLatch extends AbstractQueuedSynchronizer {
101          public boolean isSignalled() { return getState() != 0; }
# Line 130 | Line 144 | public class AbstractQueuedSynchronizerT
144          long startTime = System.nanoTime();
145          while (!sync.isQueued(t)) {
146              if (millisElapsedSince(startTime) > LONG_DELAY_MS)
147 <                throw new AssertionFailedError("timed out");
147 >                throw new AssertionError("timed out");
148              Thread.yield();
149          }
150          assertTrue(t.isAlive());
# Line 198 | Line 212 | public class AbstractQueuedSynchronizerT
212                       new HashSet<Thread>(Arrays.asList(threads)));
213      }
214  
215 <    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil };
215 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
216  
217      /**
218       * Awaits condition using the specified AwaitMethod.
# Line 214 | Line 228 | public class AbstractQueuedSynchronizerT
228              assertTrue(c.await(timeoutMillis, MILLISECONDS));
229              break;
230          case awaitNanos:
231 <            long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
232 <            long nanosRemaining = c.awaitNanos(nanosTimeout);
231 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
232 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
233              assertTrue(nanosRemaining > 0);
234              break;
235          case awaitUntil:
236              assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
237              break;
238 +        default:
239 +            throw new AssertionError();
240          }
241      }
242  
# Line 229 | Line 245 | public class AbstractQueuedSynchronizerT
245       * default timeout duration).
246       */
247      void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
248 <        long timeoutMillis = timeoutMillis();
249 <        long startTime = System.nanoTime();
248 >        final long timeoutMillis = timeoutMillis();
249 >        final long startTime;
250          try {
251              switch (awaitMethod) {
252              case awaitTimed:
253 +                startTime = System.nanoTime();
254                  assertFalse(c.await(timeoutMillis, MILLISECONDS));
255 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
256                  break;
257              case awaitNanos:
258 <                long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
259 <                long nanosRemaining = c.awaitNanos(nanosTimeout);
258 >                startTime = System.nanoTime();
259 >                long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
260 >                long nanosRemaining = c.awaitNanos(timeoutNanos);
261                  assertTrue(nanosRemaining <= 0);
262 +                assertTrue(nanosRemaining > -MILLISECONDS.toNanos(LONG_DELAY_MS));
263 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
264                  break;
265              case awaitUntil:
266 +                // We shouldn't assume that nanoTime and currentTimeMillis
267 +                // use the same time source, so don't use nanoTime here.
268 +                java.util.Date delayedDate = delayedDate(timeoutMillis);
269                  assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
270 +                assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
271                  break;
272              default:
273                  throw new UnsupportedOperationException();
274              }
275          } catch (InterruptedException ie) { threadUnexpectedException(ie); }
251        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
276      }
277  
278      /**
# Line 951 | Line 975 | public class AbstractQueuedSynchronizerT
975       */
976      public void testAwaitUninterruptibly() {
977          final Mutex sync = new Mutex();
978 <        final ConditionObject c = sync.newCondition();
978 >        final ConditionObject condition = sync.newCondition();
979          final BooleanLatch pleaseInterrupt = new BooleanLatch();
980          Thread t = newStartedThread(new CheckedRunnable() {
981              public void realRun() {
982                  sync.acquire();
983                  assertTrue(pleaseInterrupt.releaseShared(0));
984 <                c.awaitUninterruptibly();
984 >                condition.awaitUninterruptibly();
985                  assertTrue(Thread.interrupted());
986 <                assertHasWaitersLocked(sync, c, NO_THREADS);
986 >                assertHasWaitersLocked(sync, condition, NO_THREADS);
987                  sync.release();
988              }});
989  
990          pleaseInterrupt.acquireShared(0);
991          sync.acquire();
992 <        assertHasWaitersLocked(sync, c, t);
992 >        assertHasWaitersLocked(sync, condition, t);
993          sync.release();
994          t.interrupt();
995 <        assertHasWaitersUnlocked(sync, c, t);
996 <        assertThreadStaysAlive(t);
995 >        assertHasWaitersUnlocked(sync, condition, t);
996 >        assertThreadBlocks(t, Thread.State.WAITING);
997          sync.acquire();
998 <        assertHasWaitersLocked(sync, c, t);
998 >        assertHasWaitersLocked(sync, condition, t);
999          assertHasExclusiveQueuedThreads(sync, NO_THREADS);
1000 <        c.signal();
1001 <        assertHasWaitersLocked(sync, c, NO_THREADS);
1000 >        condition.signal();
1001 >        assertHasWaitersLocked(sync, condition, NO_THREADS);
1002          assertHasExclusiveQueuedThreads(sync, t);
1003          sync.release();
1004          awaitTermination(t);
# Line 1117 | Line 1141 | public class AbstractQueuedSynchronizerT
1141  
1142          waitForQueuedThread(l, t);
1143          assertFalse(l.isSignalled());
1144 <        assertThreadStaysAlive(t);
1144 >        assertThreadBlocks(t, Thread.State.WAITING);
1145          assertHasSharedQueuedThreads(l, t);
1146          assertTrue(l.releaseShared(0));
1147          assertTrue(l.isSignalled());
# Line 1142 | Line 1166 | public class AbstractQueuedSynchronizerT
1166  
1167          waitForQueuedThread(l, t);
1168          assertFalse(l.isSignalled());
1169 <        assertThreadStaysAlive(t);
1169 >        assertThreadBlocks(t, Thread.State.TIMED_WAITING);
1170          assertTrue(l.releaseShared(0));
1171          assertTrue(l.isSignalled());
1172          awaitTermination(t);
# Line 1191 | Line 1215 | public class AbstractQueuedSynchronizerT
1215      public void testTryAcquireSharedNanos_Timeout() {
1216          final BooleanLatch l = new BooleanLatch();
1217          final BooleanLatch observedQueued = new BooleanLatch();
1194        final long timeoutMillis = timeoutMillis();
1218          Thread t = newStartedThread(new CheckedRunnable() {
1219              public void realRun() throws InterruptedException {
1220                  assertFalse(l.isSignalled());
# Line 1213 | Line 1236 | public class AbstractQueuedSynchronizerT
1236          assertFalse(l.isSignalled());
1237      }
1238  
1239 +    /**
1240 +     * awaitNanos/timed await with 0 wait times out immediately
1241 +     */
1242 +    public void testAwait_Zero() throws InterruptedException {
1243 +        final Mutex sync = new Mutex();
1244 +        final ConditionObject c = sync.newCondition();
1245 +        sync.acquire();
1246 +        assertTrue(c.awaitNanos(0L) <= 0);
1247 +        assertFalse(c.await(0L, NANOSECONDS));
1248 +        sync.release();
1249 +    }
1250 +
1251 +    /**
1252 +     * awaitNanos/timed await with maximum negative wait times does not underflow
1253 +     */
1254 +    public void testAwait_NegativeInfinity() throws InterruptedException {
1255 +        final Mutex sync = new Mutex();
1256 +        final ConditionObject c = sync.newCondition();
1257 +        sync.acquire();
1258 +        assertTrue(c.awaitNanos(Long.MIN_VALUE) <= 0);
1259 +        assertFalse(c.await(Long.MIN_VALUE, NANOSECONDS));
1260 +        sync.release();
1261 +    }
1262 +
1263 +    /**
1264 +     * JDK-8191483: AbstractQueuedSynchronizer cancel/cancel race
1265 +     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testCancelCancelRace -Djsr166.runsPerTest=100 tck
1266 +     */
1267 +    public void testCancelCancelRace() throws InterruptedException {
1268 +        class Sync extends AbstractQueuedSynchronizer {
1269 +            protected boolean tryAcquire(int acquires) {
1270 +                return !hasQueuedPredecessors() && compareAndSetState(0, 1);
1271 +            }
1272 +            protected boolean tryRelease(int releases) {
1273 +                return compareAndSetState(1, 0);
1274 +            }
1275 +        }
1276 +
1277 +        Sync s = new Sync();
1278 +        s.acquire(1);           // acquire to force other threads to enqueue
1279 +
1280 +        // try to trigger double cancel race with two background threads
1281 +        ArrayList<Thread> threads = new ArrayList<>();
1282 +        Runnable failedAcquire = () -> {
1283 +            try {
1284 +                s.acquireInterruptibly(1);
1285 +                shouldThrow();
1286 +            } catch (InterruptedException success) {}
1287 +        };
1288 +        for (int i = 0; i < 2; i++) {
1289 +            Thread thread = new Thread(failedAcquire);
1290 +            thread.start();
1291 +            threads.add(thread);
1292 +        }
1293 +        Thread.sleep(100);
1294 +        for (Thread thread : threads) thread.interrupt();
1295 +        for (Thread thread : threads) awaitTermination(thread);
1296 +
1297 +        s.release(1);
1298 +
1299 +        // no one holds lock now, we should be able to acquire
1300 +        if (!s.tryAcquire(1))
1301 +            throw new RuntimeException(
1302 +                String.format(
1303 +                    "Broken: hasQueuedPredecessors=%s hasQueuedThreads=%s queueLength=%d firstQueuedThread=%s",
1304 +                    s.hasQueuedPredecessors(),
1305 +                    s.hasQueuedThreads(),
1306 +                    s.getQueueLength(),
1307 +                    s.getFirstQueuedThread()));
1308 +    }
1309 +
1310 +    /**
1311 +     * Tests scenario for
1312 +     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1313 +     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testInterruptedFailingAcquire -Djsr166.runsPerTest=10000 tck
1314 +     */
1315 +    public void testInterruptedFailingAcquire() throws Throwable {
1316 +        class PleaseThrow extends RuntimeException {}
1317 +        final PleaseThrow ex = new PleaseThrow();
1318 +        final AtomicBoolean thrown = new AtomicBoolean();
1319 +
1320 +        // A synchronizer only offering a choice of failure modes
1321 +        class Sync extends AbstractQueuedSynchronizer {
1322 +            volatile boolean pleaseThrow;
1323 +            void maybeThrow() {
1324 +                if (pleaseThrow) {
1325 +                    // assert: tryAcquire methods can throw at most once
1326 +                    if (! thrown.compareAndSet(false, true))
1327 +                        throw new AssertionError();
1328 +                    throw ex;
1329 +                }
1330 +            }
1331 +
1332 +            @Override protected boolean tryAcquire(int ignored) {
1333 +                maybeThrow();
1334 +                return false;
1335 +            }
1336 +            @Override protected int tryAcquireShared(int ignored) {
1337 +                maybeThrow();
1338 +                return -1;
1339 +            }
1340 +            @Override protected boolean tryRelease(int ignored) {
1341 +                return true;
1342 +            }
1343 +            @Override protected boolean tryReleaseShared(int ignored) {
1344 +                return true;
1345 +            }
1346 +        }
1347 +
1348 +        final Sync s = new Sync();
1349 +        final boolean acquireInterruptibly = randomBoolean();
1350 +        final Action[] uninterruptibleAcquireActions = {
1351 +            () -> s.acquire(1),
1352 +            () -> s.acquireShared(1),
1353 +        };
1354 +        final long nanosTimeout = MILLISECONDS.toNanos(2 * LONG_DELAY_MS);
1355 +        final Action[] interruptibleAcquireActions = {
1356 +            () -> s.acquireInterruptibly(1),
1357 +            () -> s.acquireSharedInterruptibly(1),
1358 +            () -> s.tryAcquireNanos(1, nanosTimeout),
1359 +            () -> s.tryAcquireSharedNanos(1, nanosTimeout),
1360 +        };
1361 +        final Action[] releaseActions = {
1362 +            () -> s.release(1),
1363 +            () -> s.releaseShared(1),
1364 +        };
1365 +        final Action acquireAction = acquireInterruptibly
1366 +            ? chooseRandomly(interruptibleAcquireActions)
1367 +            : chooseRandomly(uninterruptibleAcquireActions);
1368 +        final Action releaseAction
1369 +            = chooseRandomly(releaseActions);
1370 +
1371 +        // From os_posix.cpp:
1372 +        //
1373 +        // NOTE that since there is no "lock" around the interrupt and
1374 +        // is_interrupted operations, there is the possibility that the
1375 +        // interrupted flag (in osThread) will be "false" but that the
1376 +        // low-level events will be in the signaled state. This is
1377 +        // intentional. The effect of this is that Object.wait() and
1378 +        // LockSupport.park() will appear to have a spurious wakeup, which
1379 +        // is allowed and not harmful, and the possibility is so rare that
1380 +        // it is not worth the added complexity to add yet another lock.
1381 +        final Thread thread = newStartedThread(new CheckedRunnable() {
1382 +            public void realRun() throws Throwable {
1383 +                try {
1384 +                    acquireAction.run();
1385 +                    shouldThrow();
1386 +                } catch (InterruptedException possible) {
1387 +                    assertTrue(acquireInterruptibly);
1388 +                    assertFalse(Thread.interrupted());
1389 +                } catch (PleaseThrow possible) {
1390 +                    awaitInterrupted();
1391 +                }
1392 +            }});
1393 +        for (long startTime = 0L;; ) {
1394 +            waitForThreadToEnterWaitState(thread);
1395 +            if (s.getFirstQueuedThread() == thread
1396 +                && s.hasQueuedPredecessors()
1397 +                && s.hasQueuedThreads()
1398 +                && s.getQueueLength() == 1
1399 +                && s.hasContended())
1400 +                break;
1401 +            if (startTime == 0L)
1402 +                startTime = System.nanoTime();
1403 +            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1404 +                fail("timed out waiting for AQS state: "
1405 +                     + "thread state=" + thread.getState()
1406 +                     + ", queued threads=" + s.getQueuedThreads());
1407 +            Thread.yield();
1408 +        }
1409 +
1410 +        s.pleaseThrow = true;
1411 +        // release and interrupt, in random order
1412 +        if (randomBoolean()) {
1413 +            thread.interrupt();
1414 +            releaseAction.run();
1415 +        } else {
1416 +            releaseAction.run();
1417 +            thread.interrupt();
1418 +        }
1419 +        awaitTermination(thread);
1420 +
1421 +        if (! acquireInterruptibly)
1422 +            assertTrue(thrown.get());
1423 +
1424 +        assertNull(s.getFirstQueuedThread());
1425 +        assertFalse(s.hasQueuedPredecessors());
1426 +        assertFalse(s.hasQueuedThreads());
1427 +        assertEquals(0, s.getQueueLength());
1428 +        assertTrue(s.getQueuedThreads().isEmpty());
1429 +        assertTrue(s.hasContended());
1430 +    }
1431 +
1432   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines