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.52 by jsr166, Fri Jul 3 05:48:30 2015 UTC vs.
Revision 1.60 by jsr166, Mon Nov 27 23:06:53 2017 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          main(suite(), args);
# 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 238 | Line 246 | public class AbstractQueuedSynchronizerT
246       * default timeout duration).
247       */
248      void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
249 <        long timeoutMillis = timeoutMillis();
250 <        long startTime;
249 >        final long timeoutMillis = timeoutMillis();
250 >        final long startTime;
251          try {
252              switch (awaitMethod) {
253              case awaitTimed:
# Line 258 | Line 266 | public class AbstractQueuedSynchronizerT
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());
269 >                java.util.Date delayedDate = delayedDate(timeoutMillis);
270                  assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
271                  assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
272                  break;
# Line 968 | 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 1134 | 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 1159 | 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 1253 | Line 1261 | public class AbstractQueuedSynchronizerT
1261          sync.release();
1262      }
1263  
1264 +    /**
1265 +     * Disabled demo test for (unfixed as of 2017-11)
1266 +     * JDK-8191483: AbstractQueuedSynchronizer cancel/cancel race
1267 +     * ant -Djsr166.tckTestClass=AbstractQueuedSynchronizerTest -Djsr166.methodFilter=testCancelCancelRace -Djsr166.runsPerTest=100 tck
1268 +     */
1269 +    public void XXXXtestCancelCancelRace() throws InterruptedException {
1270 +        class Sync extends AbstractQueuedSynchronizer {
1271 +            protected boolean tryAcquire(int acquires) {
1272 +                return !hasQueuedPredecessors() && compareAndSetState(0, 1);
1273 +            }
1274 +            protected boolean tryRelease(int releases) {
1275 +                return compareAndSetState(1, 0);
1276 +            }
1277 +        }
1278 +
1279 +        Sync s = new Sync();
1280 +        s.acquire(1);           // acquire to force other threads to enqueue
1281 +
1282 +        // try to trigger double cancel race with two background threads
1283 +        ArrayList<Thread> threads = new ArrayList<>();
1284 +        Runnable failedAcquire = () -> {
1285 +            try {
1286 +                s.acquireInterruptibly(1);
1287 +                shouldThrow();
1288 +            } catch (InterruptedException expected) {}
1289 +        };
1290 +        for (int i = 0; i < 2; i++) {
1291 +            Thread thread = new Thread(failedAcquire);
1292 +            thread.start();
1293 +            threads.add(thread);
1294 +        }
1295 +        Thread.sleep(100);
1296 +        for (Thread thread : threads) thread.interrupt();
1297 +        for (Thread thread : threads) awaitTermination(thread);
1298 +
1299 +        s.release(1);
1300 +
1301 +        // no one holds lock now, we should be able to acquire
1302 +        if (!s.tryAcquire(1))
1303 +            throw new RuntimeException(
1304 +                String.format(
1305 +                    "Broken: hasQueuedPredecessors=%s hasQueuedThreads=%s queueLength=%d firstQueuedThread=%s",
1306 +                    s.hasQueuedPredecessors(),
1307 +                    s.hasQueuedThreads(),
1308 +                    s.getQueueLength(),
1309 +                    s.getFirstQueuedThread()));
1310 +    }
1311 +
1312 +    /**
1313 +     * Tests scenario for
1314 +     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1315 +     */
1316 +    public void testInterruptedFailingAcquire() throws InterruptedException {
1317 +        final RuntimeException ex = new RuntimeException();
1318 +
1319 +        // A synchronizer only offering a choice of failure modes
1320 +        class Sync extends AbstractQueuedSynchronizer {
1321 +            boolean pleaseThrow;
1322 +            @Override protected boolean tryAcquire(int ignored) {
1323 +                if (pleaseThrow) throw ex;
1324 +                return false;
1325 +            }
1326 +            @Override protected int tryAcquireShared(int ignored) {
1327 +                if (pleaseThrow) throw ex;
1328 +                return -1;
1329 +            }
1330 +            @Override protected boolean tryRelease(int ignored) {
1331 +                return true;
1332 +            }
1333 +            @Override protected boolean tryReleaseShared(int ignored) {
1334 +                return true;
1335 +            }
1336 +        }
1337 +
1338 +        final Sync s = new Sync();
1339 +
1340 +        final Thread thread = newStartedThread(new CheckedRunnable() {
1341 +            public void realRun() {
1342 +                try {
1343 +                    if (ThreadLocalRandom.current().nextBoolean())
1344 +                        s.acquire(1);
1345 +                    else
1346 +                        s.acquireShared(1);
1347 +                    shouldThrow();
1348 +                } catch (Throwable t) {
1349 +                    assertSame(ex, t);
1350 +                    assertTrue(Thread.interrupted());
1351 +                }
1352 +            }});
1353 +        waitForThreadToEnterWaitState(thread);
1354 +        assertSame(thread, s.getFirstQueuedThread());
1355 +        assertTrue(s.hasQueuedPredecessors());
1356 +        assertTrue(s.hasQueuedThreads());
1357 +        assertEquals(1, s.getQueueLength());
1358 +
1359 +        s.pleaseThrow = true;
1360 +        thread.interrupt();
1361 +        s.release(1);
1362 +        awaitTermination(thread);
1363 +    }
1364 +
1365   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines