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

Comparing jsr166/src/test/tck/AbstractQueuedLongSynchronizerTest.java (file contents):
Revision 1.29 by jsr166, Wed Dec 31 19:05:42 2014 UTC vs.
Revision 1.53 by jsr166, Fri Aug 16 02:32:26 2019 UTC

# Line 12 | Line 12 | import static java.util.concurrent.TimeU
12   import java.util.Arrays;
13   import java.util.Collection;
14   import java.util.HashSet;
15 + import java.util.concurrent.atomic.AtomicBoolean;
16   import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
17   import java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject;
18  
18 import junit.framework.AssertionFailedError;
19   import junit.framework.Test;
20   import junit.framework.TestSuite;
21  
22 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
23   public class AbstractQueuedLongSynchronizerTest 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(AbstractQueuedLongSynchronizerTest.class);
# Line 30 | Line 31 | public class AbstractQueuedLongSynchroni
31      /**
32       * A simple mutex class, adapted from the class javadoc.  Exclusive
33       * acquire tests exercise this as a sample user extension.
34 +     *
35 +     * Unlike the javadoc sample, we don't track owner thread via
36 +     * AbstractOwnableSynchronizer methods.
37       */
38      static class Mutex extends AbstractQueuedLongSynchronizer {
39          /** An eccentric value > 32 bits for locked synchronizer state. */
# Line 37 | Line 41 | public class AbstractQueuedLongSynchroni
41  
42          static final long UNLOCKED = 0;
43  
44 <        public boolean isHeldExclusively() {
44 >        /** Owner thread is untracked, so this is really just isLocked(). */
45 >        @Override public boolean isHeldExclusively() {
46              long state = getState();
47              assertTrue(state == UNLOCKED || state == LOCKED);
48              return state == LOCKED;
49          }
50  
51 <        public boolean tryAcquire(long acquires) {
51 >        @Override protected boolean tryAcquire(long acquires) {
52              assertEquals(LOCKED, acquires);
53              return compareAndSetState(UNLOCKED, LOCKED);
54          }
55  
56 <        public boolean tryRelease(long releases) {
56 >        @Override protected boolean tryRelease(long releases) {
57              if (getState() != LOCKED) throw new IllegalMonitorStateException();
58              setState(UNLOCKED);
59              return true;
# Line 78 | Line 83 | public class AbstractQueuedLongSynchroni
83              release(LOCKED);
84          }
85  
86 +        /** Faux-Implements Lock.newCondition(). */
87          public ConditionObject newCondition() {
88              return new ConditionObject();
89          }
90      }
91  
92      /**
93 <     * A simple latch class, to test shared mode.
93 >     * A minimal latch class, to test shared mode.
94       */
95      static class BooleanLatch extends AbstractQueuedLongSynchronizer {
96          public boolean isSignalled() { return getState() != 0; }
# Line 94 | Line 100 | public class AbstractQueuedLongSynchroni
100          }
101  
102          public boolean tryReleaseShared(long ignore) {
103 <            setState(1 << 62);
103 >            setState(1L << 62);
104              return true;
105          }
106      }
# Line 134 | Line 140 | public class AbstractQueuedLongSynchroni
140          long startTime = System.nanoTime();
141          while (!sync.isQueued(t)) {
142              if (millisElapsedSince(startTime) > LONG_DELAY_MS)
143 <                throw new AssertionFailedError("timed out");
143 >                throw new AssertionError("timed out");
144              Thread.yield();
145          }
146          assertTrue(t.isAlive());
# Line 202 | Line 208 | public class AbstractQueuedLongSynchroni
208                       new HashSet<Thread>(Arrays.asList(threads)));
209      }
210  
211 <    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil };
211 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
212  
213      /**
214       * Awaits condition using the specified AwaitMethod.
# Line 218 | Line 224 | public class AbstractQueuedLongSynchroni
224              assertTrue(c.await(timeoutMillis, MILLISECONDS));
225              break;
226          case awaitNanos:
227 <            long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
228 <            long nanosRemaining = c.awaitNanos(nanosTimeout);
227 >            long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
228 >            long nanosRemaining = c.awaitNanos(timeoutNanos);
229              assertTrue(nanosRemaining > 0);
230              break;
231          case awaitUntil:
232              assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
233              break;
234 +        default:
235 +            throw new AssertionError();
236          }
237      }
238  
# Line 233 | Line 241 | public class AbstractQueuedLongSynchroni
241       * default timeout duration).
242       */
243      void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
244 <        long timeoutMillis = timeoutMillis();
245 <        long startTime = System.nanoTime();
244 >        final long timeoutMillis = timeoutMillis();
245 >        final long startTime;
246          try {
247              switch (awaitMethod) {
248              case awaitTimed:
249 +                startTime = System.nanoTime();
250                  assertFalse(c.await(timeoutMillis, MILLISECONDS));
251 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
252                  break;
253              case awaitNanos:
254 <                long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
255 <                long nanosRemaining = c.awaitNanos(nanosTimeout);
254 >                startTime = System.nanoTime();
255 >                long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
256 >                long nanosRemaining = c.awaitNanos(timeoutNanos);
257                  assertTrue(nanosRemaining <= 0);
258 +                assertTrue(nanosRemaining > -MILLISECONDS.toNanos(LONG_DELAY_MS));
259 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
260                  break;
261              case awaitUntil:
262 +                // We shouldn't assume that nanoTime and currentTimeMillis
263 +                // use the same time source, so don't use nanoTime here.
264 +                java.util.Date delayedDate = delayedDate(timeoutMillis);
265                  assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
266 +                assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
267                  break;
268              default:
269                  throw new UnsupportedOperationException();
270              }
271          } catch (InterruptedException ie) { threadUnexpectedException(ie); }
255        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
272      }
273  
274      /**
# Line 955 | Line 971 | public class AbstractQueuedLongSynchroni
971       */
972      public void testAwaitUninterruptibly() {
973          final Mutex sync = new Mutex();
974 <        final ConditionObject c = sync.newCondition();
974 >        final ConditionObject condition = sync.newCondition();
975          final BooleanLatch pleaseInterrupt = new BooleanLatch();
976          Thread t = newStartedThread(new CheckedRunnable() {
977              public void realRun() {
978                  sync.acquire();
979                  assertTrue(pleaseInterrupt.releaseShared(0));
980 <                c.awaitUninterruptibly();
980 >                condition.awaitUninterruptibly();
981                  assertTrue(Thread.interrupted());
982 <                assertHasWaitersLocked(sync, c, NO_THREADS);
982 >                assertHasWaitersLocked(sync, condition, NO_THREADS);
983                  sync.release();
984              }});
985  
986          pleaseInterrupt.acquireShared(0);
987          sync.acquire();
988 <        assertHasWaitersLocked(sync, c, t);
988 >        assertHasWaitersLocked(sync, condition, t);
989          sync.release();
990          t.interrupt();
991 <        assertHasWaitersUnlocked(sync, c, t);
992 <        assertThreadStaysAlive(t);
991 >        assertHasWaitersUnlocked(sync, condition, t);
992 >        assertThreadBlocks(t, Thread.State.WAITING);
993          sync.acquire();
994 <        assertHasWaitersLocked(sync, c, t);
994 >        assertHasWaitersLocked(sync, condition, t);
995          assertHasExclusiveQueuedThreads(sync, NO_THREADS);
996 <        c.signal();
997 <        assertHasWaitersLocked(sync, c, NO_THREADS);
996 >        condition.signal();
997 >        assertHasWaitersLocked(sync, condition, NO_THREADS);
998          assertHasExclusiveQueuedThreads(sync, t);
999          sync.release();
1000          awaitTermination(t);
# Line 1121 | Line 1137 | public class AbstractQueuedLongSynchroni
1137  
1138          waitForQueuedThread(l, t);
1139          assertFalse(l.isSignalled());
1140 <        assertThreadStaysAlive(t);
1140 >        assertThreadBlocks(t, Thread.State.WAITING);
1141          assertHasSharedQueuedThreads(l, t);
1142          assertTrue(l.releaseShared(0));
1143          assertTrue(l.isSignalled());
# Line 1146 | Line 1162 | public class AbstractQueuedLongSynchroni
1162  
1163          waitForQueuedThread(l, t);
1164          assertFalse(l.isSignalled());
1165 <        assertThreadStaysAlive(t);
1165 >        assertThreadBlocks(t, Thread.State.TIMED_WAITING);
1166          assertTrue(l.releaseShared(0));
1167          assertTrue(l.isSignalled());
1168          awaitTermination(t);
# Line 1195 | Line 1211 | public class AbstractQueuedLongSynchroni
1211      public void testTryAcquireSharedNanos_Timeout() {
1212          final BooleanLatch l = new BooleanLatch();
1213          final BooleanLatch observedQueued = new BooleanLatch();
1198        final long timeoutMillis = timeoutMillis();
1214          Thread t = newStartedThread(new CheckedRunnable() {
1215              public void realRun() throws InterruptedException {
1216                  assertFalse(l.isSignalled());
# Line 1241 | Line 1256 | public class AbstractQueuedLongSynchroni
1256          sync.release();
1257      }
1258  
1259 +    /**
1260 +     * Tests scenario for
1261 +     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1262 +     * ant -Djsr166.tckTestClass=AbstractQueuedLongSynchronizerTest -Djsr166.methodFilter=testInterruptedFailingAcquire -Djsr166.runsPerTest=10000 tck
1263 +     */
1264 +    public void testInterruptedFailingAcquire() throws Throwable {
1265 +        class PleaseThrow extends RuntimeException {}
1266 +        final PleaseThrow ex = new PleaseThrow();
1267 +        final AtomicBoolean thrown = new AtomicBoolean();
1268 +
1269 +        // A synchronizer only offering a choice of failure modes
1270 +        class Sync extends AbstractQueuedLongSynchronizer {
1271 +            volatile boolean pleaseThrow;
1272 +            void maybeThrow() {
1273 +                if (pleaseThrow) {
1274 +                    // assert: tryAcquire methods can throw at most once
1275 +                    if (! thrown.compareAndSet(false, true))
1276 +                        throw new AssertionError();
1277 +                    throw ex;
1278 +                }
1279 +            }
1280 +
1281 +            @Override protected boolean tryAcquire(long ignored) {
1282 +                maybeThrow();
1283 +                return false;
1284 +            }
1285 +            @Override protected long tryAcquireShared(long ignored) {
1286 +                maybeThrow();
1287 +                return -1;
1288 +            }
1289 +            @Override protected boolean tryRelease(long ignored) {
1290 +                return true;
1291 +            }
1292 +            @Override protected boolean tryReleaseShared(long ignored) {
1293 +                return true;
1294 +            }
1295 +        }
1296 +
1297 +        final Sync s = new Sync();
1298 +        final boolean acquireInterruptibly = randomBoolean();
1299 +        final Action[] uninterruptibleAcquireActions = {
1300 +            () -> s.acquire(1),
1301 +            () -> s.acquireShared(1),
1302 +        };
1303 +        final long nanosTimeout = MILLISECONDS.toNanos(2 * LONG_DELAY_MS);
1304 +        final Action[] interruptibleAcquireActions = {
1305 +            () -> s.acquireInterruptibly(1),
1306 +            () -> s.acquireSharedInterruptibly(1),
1307 +            () -> s.tryAcquireNanos(1, nanosTimeout),
1308 +            () -> s.tryAcquireSharedNanos(1, nanosTimeout),
1309 +        };
1310 +        final Action[] releaseActions = {
1311 +            () -> s.release(1),
1312 +            () -> s.releaseShared(1),
1313 +        };
1314 +        final Action acquireAction = acquireInterruptibly
1315 +            ? chooseRandomly(interruptibleAcquireActions)
1316 +            : chooseRandomly(uninterruptibleAcquireActions);
1317 +        final Action releaseAction
1318 +            = chooseRandomly(releaseActions);
1319 +
1320 +        // From os_posix.cpp:
1321 +        //
1322 +        // NOTE that since there is no "lock" around the interrupt and
1323 +        // is_interrupted operations, there is the possibility that the
1324 +        // interrupted flag (in osThread) will be "false" but that the
1325 +        // low-level events will be in the signaled state. This is
1326 +        // intentional. The effect of this is that Object.wait() and
1327 +        // LockSupport.park() will appear to have a spurious wakeup, which
1328 +        // is allowed and not harmful, and the possibility is so rare that
1329 +        // it is not worth the added complexity to add yet another lock.
1330 +        final Thread thread = newStartedThread(new CheckedRunnable() {
1331 +            public void realRun() throws Throwable {
1332 +                try {
1333 +                    acquireAction.run();
1334 +                    shouldThrow();
1335 +                } catch (InterruptedException possible) {
1336 +                    assertTrue(acquireInterruptibly);
1337 +                    assertFalse(Thread.interrupted());
1338 +                } catch (PleaseThrow possible) {
1339 +                    awaitInterrupted();
1340 +                }
1341 +            }});
1342 +        for (long startTime = 0L;; ) {
1343 +            waitForThreadToEnterWaitState(thread);
1344 +            if (s.getFirstQueuedThread() == thread
1345 +                && s.hasQueuedPredecessors()
1346 +                && s.hasQueuedThreads()
1347 +                && s.getQueueLength() == 1
1348 +                && s.hasContended())
1349 +                break;
1350 +            if (startTime == 0L)
1351 +                startTime = System.nanoTime();
1352 +            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1353 +                fail("timed out waiting for AQS state: "
1354 +                     + "thread state=" + thread.getState()
1355 +                     + ", queued threads=" + s.getQueuedThreads());
1356 +            Thread.yield();
1357 +        }
1358 +
1359 +        s.pleaseThrow = true;
1360 +        // release and interrupt, in random order
1361 +        if (randomBoolean()) {
1362 +            thread.interrupt();
1363 +            releaseAction.run();
1364 +        } else {
1365 +            releaseAction.run();
1366 +            thread.interrupt();
1367 +        }
1368 +        awaitTermination(thread);
1369 +
1370 +        if (! acquireInterruptibly)
1371 +            assertTrue(thrown.get());
1372 +
1373 +        assertNull(s.getFirstQueuedThread());
1374 +        assertFalse(s.hasQueuedPredecessors());
1375 +        assertFalse(s.hasQueuedThreads());
1376 +        assertEquals(0, s.getQueueLength());
1377 +        assertTrue(s.getQueuedThreads().isEmpty());
1378 +        assertTrue(s.hasContended());
1379 +    }
1380 +
1381   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines