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.25 by jsr166, Fri Jun 3 05:07:14 2011 UTC vs.
Revision 1.43 by jsr166, Mon Nov 27 23:06:53 2017 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.Arrays;
13 + import java.util.Collection;
14 + import java.util.HashSet;
15 + import java.util.concurrent.ThreadLocalRandom;
16   import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
17   import java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject;
18  
19 + import junit.framework.AssertionFailedError;
20 + import junit.framework.Test;
21 + import junit.framework.TestSuite;
22 +
23 + @SuppressWarnings("WaitNotInLoop") // we implement spurious-wakeup freedom
24   public class AbstractQueuedLongSynchronizerTest 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(AbstractQueuedLongSynchronizerTest.class);
# Line 23 | Line 32 | public class AbstractQueuedLongSynchroni
32      /**
33       * A simple mutex class, adapted from the class javadoc.  Exclusive
34       * acquire tests exercise this as a sample user extension.
35 +     *
36 +     * Unlike the javadoc sample, we don't track owner thread via
37 +     * AbstractOwnableSynchronizer methods.
38       */
39      static class Mutex extends AbstractQueuedLongSynchronizer {
40          /** An eccentric value > 32 bits for locked synchronizer state. */
# Line 30 | Line 42 | public class AbstractQueuedLongSynchroni
42  
43          static final long UNLOCKED = 0;
44  
45 <        public boolean isHeldExclusively() {
45 >        /** Owner thread is untracked, so this is really just isLocked(). */
46 >        @Override public boolean isHeldExclusively() {
47              long state = getState();
48              assertTrue(state == UNLOCKED || state == LOCKED);
49              return state == LOCKED;
50          }
51  
52 <        public boolean tryAcquire(long acquires) {
52 >        @Override protected boolean tryAcquire(long acquires) {
53              assertEquals(LOCKED, acquires);
54              return compareAndSetState(UNLOCKED, LOCKED);
55          }
56  
57 <        public boolean tryRelease(long releases) {
57 >        @Override protected boolean tryRelease(long releases) {
58              if (getState() != LOCKED) throw new IllegalMonitorStateException();
59              setState(UNLOCKED);
60              return true;
# Line 71 | Line 84 | public class AbstractQueuedLongSynchroni
84              release(LOCKED);
85          }
86  
87 +        /** Faux-Implements Lock.newCondition(). */
88          public ConditionObject newCondition() {
89              return new ConditionObject();
90          }
91      }
92  
93      /**
94 <     * A simple latch class, to test shared mode.
94 >     * A minimal latch class, to test shared mode.
95       */
96      static class BooleanLatch extends AbstractQueuedLongSynchronizer {
97          public boolean isSignalled() { return getState() != 0; }
# Line 87 | Line 101 | public class AbstractQueuedLongSynchroni
101          }
102  
103          public boolean tryReleaseShared(long ignore) {
104 <            setState(1 << 62);
104 >            setState(1L << 62);
105              return true;
106          }
107      }
# Line 117 | Line 131 | public class AbstractQueuedLongSynchroni
131      }
132  
133      /** A constant to clarify calls to checking methods below. */
134 <    final static Thread[] NO_THREADS = new Thread[0];
134 >    static final Thread[] NO_THREADS = new Thread[0];
135  
136      /**
137       * Spin-waits until sync.isQueued(t) becomes true.
# Line 195 | Line 209 | public class AbstractQueuedLongSynchroni
209                       new HashSet<Thread>(Arrays.asList(threads)));
210      }
211  
212 <    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil };
212 >    enum AwaitMethod { await, awaitTimed, awaitNanos, awaitUntil }
213  
214      /**
215       * Awaits condition using the specified AwaitMethod.
# Line 218 | Line 232 | public class AbstractQueuedLongSynchroni
232          case awaitUntil:
233              assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
234              break;
235 +        default:
236 +            throw new AssertionError();
237          }
238      }
239  
# Line 226 | Line 242 | public class AbstractQueuedLongSynchroni
242       * default timeout duration).
243       */
244      void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) {
245 <        long timeoutMillis = timeoutMillis();
246 <        long startTime = System.nanoTime();
245 >        final long timeoutMillis = timeoutMillis();
246 >        final long startTime;
247          try {
248              switch (awaitMethod) {
249              case awaitTimed:
250 +                startTime = System.nanoTime();
251                  assertFalse(c.await(timeoutMillis, MILLISECONDS));
252 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
253                  break;
254              case awaitNanos:
255 +                startTime = System.nanoTime();
256                  long nanosTimeout = MILLISECONDS.toNanos(timeoutMillis);
257                  long nanosRemaining = c.awaitNanos(nanosTimeout);
258                  assertTrue(nanosRemaining <= 0);
259 +                assertTrue(nanosRemaining > -MILLISECONDS.toNanos(LONG_DELAY_MS));
260 +                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
261                  break;
262              case awaitUntil:
263 +                // We shouldn't assume that nanoTime and currentTimeMillis
264 +                // use the same time source, so don't use nanoTime here.
265 +                java.util.Date delayedDate = delayedDate(timeoutMillis);
266                  assertFalse(c.awaitUntil(delayedDate(timeoutMillis)));
267 +                assertTrue(new java.util.Date().getTime() >= delayedDate.getTime());
268                  break;
269              default:
270                  throw new UnsupportedOperationException();
271              }
272          } catch (InterruptedException ie) { threadUnexpectedException(ie); }
248        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
273      }
274  
275      /**
# Line 948 | Line 972 | public class AbstractQueuedLongSynchroni
972       */
973      public void testAwaitUninterruptibly() {
974          final Mutex sync = new Mutex();
975 <        final ConditionObject c = sync.newCondition();
975 >        final ConditionObject condition = sync.newCondition();
976          final BooleanLatch pleaseInterrupt = new BooleanLatch();
977          Thread t = newStartedThread(new CheckedRunnable() {
978              public void realRun() {
979                  sync.acquire();
980                  assertTrue(pleaseInterrupt.releaseShared(0));
981 <                c.awaitUninterruptibly();
981 >                condition.awaitUninterruptibly();
982                  assertTrue(Thread.interrupted());
983 <                assertHasWaitersLocked(sync, c, NO_THREADS);
983 >                assertHasWaitersLocked(sync, condition, NO_THREADS);
984                  sync.release();
985              }});
986  
987          pleaseInterrupt.acquireShared(0);
988          sync.acquire();
989 <        assertHasWaitersLocked(sync, c, t);
989 >        assertHasWaitersLocked(sync, condition, t);
990          sync.release();
991          t.interrupt();
992 <        assertHasWaitersUnlocked(sync, c, t);
993 <        assertThreadStaysAlive(t);
992 >        assertHasWaitersUnlocked(sync, condition, t);
993 >        assertThreadBlocks(t, Thread.State.WAITING);
994          sync.acquire();
995 <        assertHasWaitersLocked(sync, c, t);
995 >        assertHasWaitersLocked(sync, condition, t);
996          assertHasExclusiveQueuedThreads(sync, NO_THREADS);
997 <        c.signal();
998 <        assertHasWaitersLocked(sync, c, NO_THREADS);
997 >        condition.signal();
998 >        assertHasWaitersLocked(sync, condition, NO_THREADS);
999          assertHasExclusiveQueuedThreads(sync, t);
1000          sync.release();
1001          awaitTermination(t);
# Line 1114 | Line 1138 | public class AbstractQueuedLongSynchroni
1138  
1139          waitForQueuedThread(l, t);
1140          assertFalse(l.isSignalled());
1141 <        assertThreadStaysAlive(t);
1141 >        assertThreadBlocks(t, Thread.State.WAITING);
1142          assertHasSharedQueuedThreads(l, t);
1143          assertTrue(l.releaseShared(0));
1144          assertTrue(l.isSignalled());
# Line 1139 | Line 1163 | public class AbstractQueuedLongSynchroni
1163  
1164          waitForQueuedThread(l, t);
1165          assertFalse(l.isSignalled());
1166 <        assertThreadStaysAlive(t);
1166 >        assertThreadBlocks(t, Thread.State.TIMED_WAITING);
1167          assertTrue(l.releaseShared(0));
1168          assertTrue(l.isSignalled());
1169          awaitTermination(t);
# Line 1187 | Line 1211 | public class AbstractQueuedLongSynchroni
1211       */
1212      public void testTryAcquireSharedNanos_Timeout() {
1213          final BooleanLatch l = new BooleanLatch();
1214 +        final BooleanLatch observedQueued = new BooleanLatch();
1215          Thread t = newStartedThread(new CheckedRunnable() {
1216              public void realRun() throws InterruptedException {
1217                  assertFalse(l.isSignalled());
1218 <                long startTime = System.nanoTime();
1219 <                long nanos = MILLISECONDS.toNanos(timeoutMillis());
1220 <                assertFalse(l.tryAcquireSharedNanos(0, nanos));
1221 <                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
1218 >                for (long millis = timeoutMillis();
1219 >                     !observedQueued.isSignalled();
1220 >                     millis *= 2) {
1221 >                    long nanos = MILLISECONDS.toNanos(millis);
1222 >                    long startTime = System.nanoTime();
1223 >                    assertFalse(l.tryAcquireSharedNanos(0, nanos));
1224 >                    assertTrue(millisElapsedSince(startTime) >= millis);
1225 >                }
1226                  assertFalse(l.isSignalled());
1227              }});
1228  
1229          waitForQueuedThread(l, t);
1230 +        observedQueued.releaseShared(0);
1231          assertFalse(l.isSignalled());
1232          awaitTermination(t);
1233          assertFalse(l.isSignalled());
1234      }
1235  
1236 +    /**
1237 +     * awaitNanos/timed await with 0 wait times out immediately
1238 +     */
1239 +    public void testAwait_Zero() throws InterruptedException {
1240 +        final Mutex sync = new Mutex();
1241 +        final ConditionObject c = sync.newCondition();
1242 +        sync.acquire();
1243 +        assertTrue(c.awaitNanos(0L) <= 0);
1244 +        assertFalse(c.await(0L, NANOSECONDS));
1245 +        sync.release();
1246 +    }
1247 +
1248 +    /**
1249 +     * awaitNanos/timed await with maximum negative wait times does not underflow
1250 +     */
1251 +    public void testAwait_NegativeInfinity() throws InterruptedException {
1252 +        final Mutex sync = new Mutex();
1253 +        final ConditionObject c = sync.newCondition();
1254 +        sync.acquire();
1255 +        assertTrue(c.awaitNanos(Long.MIN_VALUE) <= 0);
1256 +        assertFalse(c.await(Long.MIN_VALUE, NANOSECONDS));
1257 +        sync.release();
1258 +    }
1259 +
1260 +    /**
1261 +     * Tests scenario for
1262 +     * JDK-8191937: Lost interrupt in AbstractQueuedSynchronizer when tryAcquire methods throw
1263 +     */
1264 +    public void testInterruptedFailingAcquire() throws InterruptedException {
1265 +        final RuntimeException ex = new RuntimeException();
1266 +
1267 +        // A synchronizer only offering a choice of failure modes
1268 +        class Sync extends AbstractQueuedLongSynchronizer {
1269 +            boolean pleaseThrow;
1270 +            @Override protected boolean tryAcquire(long ignored) {
1271 +                if (pleaseThrow) throw ex;
1272 +                return false;
1273 +            }
1274 +            @Override protected long tryAcquireShared(long ignored) {
1275 +                if (pleaseThrow) throw ex;
1276 +                return -1;
1277 +            }
1278 +            @Override protected boolean tryRelease(long ignored) {
1279 +                return true;
1280 +            }
1281 +            @Override protected boolean tryReleaseShared(long ignored) {
1282 +                return true;
1283 +            }
1284 +        }
1285 +
1286 +        final Sync s = new Sync();
1287 +
1288 +        final Thread thread = newStartedThread(new CheckedRunnable() {
1289 +            public void realRun() {
1290 +                try {
1291 +                    if (ThreadLocalRandom.current().nextBoolean())
1292 +                        s.acquire(1);
1293 +                    else
1294 +                        s.acquireShared(1);
1295 +                    shouldThrow();
1296 +                } catch (Throwable t) {
1297 +                    assertSame(ex, t);
1298 +                    assertTrue(Thread.interrupted());
1299 +                }
1300 +            }});
1301 +        waitForThreadToEnterWaitState(thread);
1302 +        assertSame(thread, s.getFirstQueuedThread());
1303 +        assertTrue(s.hasQueuedPredecessors());
1304 +        assertTrue(s.hasQueuedThreads());
1305 +        assertEquals(1, s.getQueueLength());
1306 +
1307 +        s.pleaseThrow = true;
1308 +        thread.interrupt();
1309 +        s.release(1);
1310 +        awaitTermination(thread);
1311 +    }
1312 +
1313   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines