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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines