参考:http://www.cnblogs.com/skywang12345/p/3505809.html
概要
Java的JUC(java.util.concurrent)包中的锁包括"独占锁"和"共享锁"。在“Java多线程系列--“JUC锁”02之 互斥锁ReentrantLock ”中,对Java的独占锁进行了说明。本章对Java的“共享锁”进行介绍,JUC中的共享锁有CountDownLatch, CyclicBarrier, Semaphore, ReentrantReadWriteLock等;本章会以ReentrantReadWriteLock为蓝本对共享锁进行说明。内容包括:
ReadWriteLock 和 ReentrantReadWriteLock介绍
ReadWriteLock 和 ReentrantReadWriteLock函数列表
ReentrantReadWriteLock数据结构
参考代码(基于JDK1.7.0_40)
获取共享锁
释放共享锁
公平共享锁和非公平共享锁
ReentrantReadWriteLock示例
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3505809.html
ReadWriteLock 和 ReentrantReadWriteLock介绍
ReadWriteLock,顾名思义,是读写锁。它维护了一对相关的锁 — — “读取锁”和“写入锁”,一个用于读取操作,另一个用于写入操作。
“读取锁”用于只读操作,它是“共享锁”,能同时被多个线程获取。
“写入锁”用于写入操作,它是“独占锁”,写入锁只能被一个线程锁获取。
注意:不能同时存在读取锁和写入锁!
ReadWriteLock是一个接口。ReentrantReadWriteLock是它的实现类,ReentrantReadWriteLock包括子类ReadLock和WriteLock。
ReadWriteLock 和 ReentrantReadWriteLock函数列表
ReadWriteLock函数列表
// 返回用于读取操作的锁。 Lock readLock() // 返回用于写入操作的锁。 Lock writeLock()
// 创建一个新的 ReentrantReadWriteLock,默认是采用“非公平策略”。 ReentrantReadWriteLock() // 创建一个新的 ReentrantReadWriteLock,fair是“公平策略”。fair为true,意味着公平策略;否则,意味着非公平策略。 ReentrantReadWriteLock(boolean fair) // 返回当前拥有写入锁的线程,如果没有这样的线程,则返回 null。 protected Thread getOwner() // 返回一个 collection,它包含可能正在等待获取读取锁的线程。 protected Collection<Thread> getQueuedReaderThreads() // 返回一个 collection,它包含可能正在等待获取读取或写入锁的线程。 protected Collection<Thread> getQueuedThreads() // 返回一个 collection,它包含可能正在等待获取写入锁的线程。 protected Collection<Thread> getQueuedWriterThreads() // 返回等待获取读取或写入锁的线程估计数目。 int getQueueLength() // 查询当前线程在此锁上保持的重入读取锁数量。 int getReadHoldCount() // 查询为此锁保持的读取锁数量。 int getReadLockCount() // 返回一个 collection,它包含可能正在等待与写入锁相关的给定条件的那些线程。 protected Collection<Thread> getWaitingThreads(Condition condition) // 返回正等待与写入锁相关的给定条件的线程估计数目。 int getWaitQueueLength(Condition condition) // 查询当前线程在此锁上保持的重入写入锁数量。 int getWriteHoldCount() // 查询是否给定线程正在等待获取读取或写入锁。 boolean hasQueuedThread(Thread thread) // 查询是否所有的线程正在等待获取读取或写入锁。 boolean hasQueuedThreads() // 查询是否有些线程正在等待与写入锁有关的给定条件。 boolean hasWaiters(Condition condition) // 如果此锁将公平性设置为 ture,则返回 true。 boolean isFair() // 查询是否某个线程保持了写入锁。 boolean isWriteLocked() // 查询当前线程是否保持了写入锁。 boolean isWriteLockedByCurrentThread() // 返回用于读取操作的锁。 ReentrantReadWriteLock.ReadLock readLock() // 返回用于写入操作的锁。 ReentrantReadWriteLock.WriteLock writeLock()
ReentrantReadWriteLock数据结构
ReentrantReadWriteLock的UML类图如下:
从中可以看出:
(01) ReentrantReadWriteLock实现了ReadWriteLock接口。ReadWriteLock是一个读写锁的接口,提供了"获取读锁的readLock()函数" 和 "获取写锁的writeLock()函数"。
(02) ReentrantReadWriteLock中包含:sync对象,读锁readerLock和写锁writerLock。读锁ReadLock和写锁WriteLock都实现了Lock接口。读锁ReadLock和写锁WriteLock中也都分别包含了"Sync对象",它们的Sync对象和ReentrantReadWriteLock的Sync对象 是一样的,就是通过sync,读锁和写锁实现了对同一个对象的访问。
(03) 和"ReentrantLock"一样,sync是Sync类型;而且,Sync也是一个继承于AQS的抽象类。Sync也包括"公平锁"FairSync和"非公平锁"NonfairSync。sync对象是"FairSync"和"NonfairSync"中的一个,默认是"NonfairSync"。
参考代码(基于JDK1.7.0_40)
ReentrantReadWriteLock的完整源码
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /* 2 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 */ 24 25 /* 26 * 27 * 28 * 29 * 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.locks; 37 import java.util.concurrent.*; 38 import java.util.concurrent.atomic.*; 39 import java.util.*; 40 41 /** 42 * An implementation of {@link ReadWriteLock} supporting similar 43 * semantics to {@link ReentrantLock}. 44 * <p>This class has the following properties: 45 * 46 * <ul> 47 * <li><b>Acquisition order</b> 48 * 49 * <p> This class does not impose a reader or writer preference 50 * ordering for lock access. However, it does support an optional 51 * <em>fairness</em> policy. 52 * 53 * <dl> 54 * <dt><b><i>Non-fair mode (default)</i></b> 55 * <dd>When constructed as non-fair (the default), the order of entry 56 * to the read and write lock is unspecified, subject to reentrancy 57 * constraints. A nonfair lock that is continuously contended may 58 * indefinitely postpone one or more reader or writer threads, but 59 * will normally have higher throughput than a fair lock. 60 * <p> 61 * 62 * <dt><b><i>Fair mode</i></b> 63 * <dd> When constructed as fair, threads contend for entry using an 64 * approximately arrival-order policy. When the currently held lock 65 * is released either the longest-waiting single writer thread will 66 * be assigned the write lock, or if there is a group of reader threads 67 * waiting longer than all waiting writer threads, that group will be 68 * assigned the read lock. 69 * 70 * <p>A thread that tries to acquire a fair read lock (non-reentrantly) 71 * will block if either the write lock is held, or there is a waiting 72 * writer thread. The thread will not acquire the read lock until 73 * after the oldest currently waiting writer thread has acquired and 74 * released the write lock. Of course, if a waiting writer abandons 75 * its wait, leaving one or more reader threads as the longest waiters 76 * in the queue with the write lock free, then those readers will be 77 * assigned the read lock. 78 * 79 * <p>A thread that tries to acquire a fair write lock (non-reentrantly) 80 * will block unless both the read lock and write lock are free (which 81 * implies there are no waiting threads). (Note that the non-blocking 82 * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods 83 * do not honor this fair setting and will acquire the lock if it is 84 * possible, regardless of waiting threads.) 85 * <p> 86 * </dl> 87 * 88 * <li><b>Reentrancy</b> 89 * 90 * <p>This lock allows both readers and writers to reacquire read or 91 * write locks in the style of a {@link ReentrantLock}. Non-reentrant 92 * readers are not allowed until all write locks held by the writing 93 * thread have been released. 94 * 95 * <p>Additionally, a writer can acquire the read lock, but not 96 * vice-versa. Among other applications, reentrancy can be useful 97 * when write locks are held during calls or callbacks to methods that 98 * perform reads under read locks. If a reader tries to acquire the 99 * write lock it will never succeed. 100 * 101 * <li><b>Lock downgrading</b> 102 * <p>Reentrancy also allows downgrading from the write lock to a read lock, 103 * by acquiring the write lock, then the read lock and then releasing the 104 * write lock. However, upgrading from a read lock to the write lock is 105 * <b>not</b> possible. 106 * 107 * <li><b>Interruption of lock acquisition</b> 108 * <p>The read lock and write lock both support interruption during lock 109 * acquisition. 110 * 111 * <li><b>{@link Condition} support</b> 112 * <p>The write lock provides a {@link Condition} implementation that 113 * behaves in the same way, with respect to the write lock, as the 114 * {@link Condition} implementation provided by 115 * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}. 116 * This {@link Condition} can, of course, only be used with the write lock. 117 * 118 * <p>The read lock does not support a {@link Condition} and 119 * {@code readLock().newCondition()} throws 120 * {@code UnsupportedOperationException}. 121 * 122 * <li><b>Instrumentation</b> 123 * <p>This class supports methods to determine whether locks 124 * are held or contended. These methods are designed for monitoring 125 * system state, not for synchronization control. 126 * </ul> 127 * 128 * <p>Serialization of this class behaves in the same way as built-in 129 * locks: a deserialized lock is in the unlocked state, regardless of 130 * its state when serialized. 131 * 132 * <p><b>Sample usages</b>. Here is a code sketch showing how to perform 133 * lock downgrading after updating a cache (exception handling is 134 * particularly tricky when handling multiple locks in a non-nested 135 * fashion): 136 * 137 * <pre> {@code 138 * class CachedData { 139 * Object data; 140 * volatile boolean cacheValid; 141 * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); 142 * 143 * void processCachedData() { 144 * rwl.readLock().lock(); 145 * if (!cacheValid) { 146 * // Must release read lock before acquiring write lock 147 * rwl.readLock().unlock(); 148 * rwl.writeLock().lock(); 149 * try { 150 * // Recheck state because another thread might have 151 * // acquired write lock and changed state before we did. 152 * if (!cacheValid) { 153 * data = ... 154 * cacheValid = true; 155 * } 156 * // Downgrade by acquiring read lock before releasing write lock 157 * rwl.readLock().lock(); 158 * } finally { 159 * rwl.writeLock().unlock(); // Unlock write, still hold read 160 * } 161 * } 162 * 163 * try { 164 * use(data); 165 * } finally { 166 * rwl.readLock().unlock(); 167 * } 168 * } 169 * }}</pre> 170 * 171 * ReentrantReadWriteLocks can be used to improve concurrency in some 172 * uses of some kinds of Collections. This is typically worthwhile 173 * only when the collections are expected to be large, accessed by 174 * more reader threads than writer threads, and entail operations with 175 * overhead that outweighs synchronization overhead. For example, here 176 * is a class using a TreeMap that is expected to be large and 177 * concurrently accessed. 178 * 179 * <pre>{@code 180 * class RWDictionary { 181 * private final Map<String, Data> m = new TreeMap<String, Data>(); 182 * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); 183 * private final Lock r = rwl.readLock(); 184 * private final Lock w = rwl.writeLock(); 185 * 186 * public Data get(String key) { 187 * r.lock(); 188 * try { return m.get(key); } 189 * finally { r.unlock(); } 190 * } 191 * public String[] allKeys() { 192 * r.lock(); 193 * try { return m.keySet().toArray(); } 194 * finally { r.unlock(); } 195 * } 196 * public Data put(String key, Data value) { 197 * w.lock(); 198 * try { return m.put(key, value); } 199 * finally { w.unlock(); } 200 * } 201 * public void clear() { 202 * w.lock(); 203 * try { m.clear(); } 204 * finally { w.unlock(); } 205 * } 206 * }}</pre> 207 * 208 * <h3>Implementation Notes</h3> 209 * 210 * <p>This lock supports a maximum of 65535 recursive write locks 211 * and 65535 read locks. Attempts to exceed these limits result in 212 * {@link Error} throws from locking methods. 213 * 214 * @since 1.5 215 * @author Doug Lea 216 * 217 */ 218 public class ReentrantReadWriteLock 219 implements ReadWriteLock, java.io.Serializable { 220 private static final long serialVersionUID = -6992448646407690164L; 221 /** Inner class providing readlock */ 222 private final ReentrantReadWriteLock.ReadLock readerLock; 223 /** Inner class providing writelock */ 224 private final ReentrantReadWriteLock.WriteLock writerLock; 225 /** Performs all synchronization mechanics */ 226 final Sync sync; 227 228 /** 229 * Creates a new {@code ReentrantReadWriteLock} with 230 * default (nonfair) ordering properties. 231 */ 232 public ReentrantReadWriteLock() { 233 this(false); 234 } 235 236 /** 237 * Creates a new {@code ReentrantReadWriteLock} with 238 * the given fairness policy. 239 * 240 * @param fair {@code true} if this lock should use a fair ordering policy 241 */ 242 public ReentrantReadWriteLock(boolean fair) { 243 sync = fair ? new FairSync() : new NonfairSync(); 244 readerLock = new ReadLock(this); 245 writerLock = new WriteLock(this); 246 } 247 248 public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; } 249 public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; } 250 251 /** 252 * Synchronization implementation for ReentrantReadWriteLock. 253 * Subclassed into fair and nonfair versions. 254 */ 255 abstract static class Sync extends AbstractQueuedSynchronizer { 256 private static final long serialVersionUID = 6317671515068378041L; 257 258 /* 259 * Read vs write count extraction constants and functions. 260 * Lock state is logically divided into two unsigned shorts: 261 * The lower one representing the exclusive (writer) lock hold count, 262 * and the upper the shared (reader) hold count. 263 */ 264 265 static final int SHARED_SHIFT = 16; 266 static final int SHARED_UNIT = (1 << SHARED_SHIFT); 267 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; 268 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; 269 270 /** Returns the number of shared holds represented in count */ 271 static int sharedCount(int c) { return c >>> SHARED_SHIFT; } 272 /** Returns the number of exclusive holds represented in count */ 273 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } 274 275 /** 276 * A counter for per-thread read hold counts. 277 * Maintained as a ThreadLocal; cached in cachedHoldCounter 278 */ 279 static final class HoldCounter { 280 int count = 0; 281 // Use id, not reference, to avoid garbage retention 282 final long tid = Thread.currentThread().getId(); 283 } 284 285 /** 286 * ThreadLocal subclass. Easiest to explicitly define for sake 287 * of deserialization mechanics. 288 */ 289 static final class ThreadLocalHoldCounter 290 extends ThreadLocal<HoldCounter> { 291 public HoldCounter initialValue() { 292 return new HoldCounter(); 293 } 294 } 295 296 /** 297 * The number of reentrant read locks held by current thread. 298 * Initialized only in constructor and readObject. 299 * Removed whenever a thread's read hold count drops to 0. 300 */ 301 private transient ThreadLocalHoldCounter readHolds; 302 303 /** 304 * The hold count of the last thread to successfully acquire 305 * readLock. This saves ThreadLocal lookup in the common case 306 * where the next thread to release is the last one to 307 * acquire. This is non-volatile since it is just used 308 * as a heuristic, and would be great for threads to cache. 309 * 310 * <p>Can outlive the Thread for which it is caching the read 311 * hold count, but avoids garbage retention by not retaining a 312 * reference to the Thread. 313 * 314 * <p>Accessed via a benign data race; relies on the memory 315 * model's final field and out-of-thin-air guarantees. 316 */ 317 private transient HoldCounter cachedHoldCounter; 318 319 /** 320 * firstReader is the first thread to have acquired the read lock. 321 * firstReaderHoldCount is firstReader's hold count. 322 * 323 * <p>More precisely, firstReader is the unique thread that last 324 * changed the shared count from 0 to 1, and has not released the 325 * read lock since then; null if there is no such thread. 326 * 327 * <p>Cannot cause garbage retention unless the thread terminated 328 * without relinquishing its read locks, since tryReleaseShared 329 * sets it to null. 330 * 331 * <p>Accessed via a benign data race; relies on the memory 332 * model's out-of-thin-air guarantees for references. 333 * 334 * <p>This allows tracking of read holds for uncontended read 335 * locks to be very cheap. 336 */ 337 private transient Thread firstReader = null; 338 private transient int firstReaderHoldCount; 339 340 Sync() { 341 readHolds = new ThreadLocalHoldCounter(); 342 setState(getState()); // ensures visibility of readHolds 343 } 344 345 /* 346 * Acquires and releases use the same code for fair and 347 * nonfair locks, but differ in whether/how they allow barging 348 * when queues are non-empty. 349 */ 350 351 /** 352 * Returns true if the current thread, when trying to acquire 353 * the read lock, and otherwise eligible to do so, should block 354 * because of policy for overtaking other waiting threads. 355 */ 356 abstract boolean readerShouldBlock(); 357 358 /** 359 * Returns true if the current thread, when trying to acquire 360 * the write lock, and otherwise eligible to do so, should block 361 * because of policy for overtaking other waiting threads. 362 */ 363 abstract boolean writerShouldBlock(); 364 365 /* 366 * Note that tryRelease and tryAcquire can be called by 367 * Conditions. So it is possible that their arguments contain 368 * both read and write holds that are all released during a 369 * condition wait and re-established in tryAcquire. 370 */ 371 372 protected final boolean tryRelease(int releases) { 373 if (!isHeldExclusively()) 374 throw new IllegalMonitorStateException(); 375 int nextc = getState() - releases; 376 boolean free = exclusiveCount(nextc) == 0; 377 if (free) 378 setExclusiveOwnerThread(null); 379 setState(nextc); 380 return free; 381 } 382 383 protected final boolean tryAcquire(int acquires) { 384 /* 385 * Walkthrough: 386 * 1. If read count nonzero or write count nonzero 387 * and owner is a different thread, fail. 388 * 2. If count would saturate, fail. (This can only 389 * happen if count is already nonzero.) 390 * 3. Otherwise, this thread is eligible for lock if 391 * it is either a reentrant acquire or 392 * queue policy allows it. If so, update state 393 * and set owner. 394 */ 395 Thread current = Thread.currentThread(); 396 int c = getState(); 397 int w = exclusiveCount(c); 398 if (c != 0) { 399 // (Note: if c != 0 and w == 0 then shared count != 0) 400 if (w == 0 || current != getExclusiveOwnerThread()) 401 return false; 402 if (w + exclusiveCount(acquires) > MAX_COUNT) 403 throw new Error("Maximum lock count exceeded"); 404 // Reentrant acquire 405 setState(c + acquires); 406 return true; 407 } 408 if (writerShouldBlock() || 409 !compareAndSetState(c, c + acquires)) 410 return false; 411 setExclusiveOwnerThread(current); 412 return true; 413 } 414 415 protected final boolean tryReleaseShared(int unused) { 416 Thread current = Thread.currentThread(); 417 if (firstReader == current) { 418 // assert firstReaderHoldCount > 0; 419 if (firstReaderHoldCount == 1) 420 firstReader = null; 421 else 422 firstReaderHoldCount--; 423 } else { 424 HoldCounter rh = cachedHoldCounter; 425 if (rh == null || rh.tid != current.getId()) 426 rh = readHolds.get(); 427 int count = rh.count; 428 if (count <= 1) { 429 readHolds.remove(); 430 if (count <= 0) 431 throw unmatchedUnlockException(); 432 } 433 --rh.count; 434 } 435 for (;;) { 436 int c = getState(); 437 int nextc = c - SHARED_UNIT; 438 if (compareAndSetState(c, nextc)) 439 // Releasing the read lock has no effect on readers, 440 // but it may allow waiting writers to proceed if 441 // both read and write locks are now free. 442 return nextc == 0; 443 } 444 } 445 446 private IllegalMonitorStateException unmatchedUnlockException() { 447 return new IllegalMonitorStateException( 448 "attempt to unlock read lock, not locked by current thread"); 449 } 450 451 protected final int tryAcquireShared(int unused) { 452 /* 453 * Walkthrough: 454 * 1. If write lock held by another thread, fail. 455 * 2. Otherwise, this thread is eligible for 456 * lock wrt state, so ask if it should block 457 * because of queue policy. If not, try 458 * to grant by CASing state and updating count. 459 * Note that step does not check for reentrant 460 * acquires, which is postponed to full version 461 * to avoid having to check hold count in 462 * the more typical non-reentrant case. 463 * 3. If step 2 fails either because thread 464 * apparently not eligible or CAS fails or count 465 * saturated, chain to version with full retry loop. 466 */ 467 Thread current = Thread.currentThread(); 468 int c = getState(); 469 if (exclusiveCount(c) != 0 && 470 getExclusiveOwnerThread() != current) 471 return -1; 472 int r = sharedCount(c); 473 if (!readerShouldBlock() && 474 r < MAX_COUNT && 475 compareAndSetState(c, c + SHARED_UNIT)) { 476 if (r == 0) { 477 firstReader = current; 478 firstReaderHoldCount = 1; 479 } else if (firstReader == current) { 480 firstReaderHoldCount++; 481 } else { 482 HoldCounter rh = cachedHoldCounter; 483 if (rh == null || rh.tid != current.getId()) 484 cachedHoldCounter = rh = readHolds.get(); 485 else if (rh.count == 0) 486 readHolds.set(rh); 487 rh.count++; 488 } 489 return 1; 490 } 491 return fullTryAcquireShared(current); 492 } 493 494 /** 495 * Full version of acquire for reads, that handles CAS misses 496 * and reentrant reads not dealt with in tryAcquireShared. 497 */ 498 final int fullTryAcquireShared(Thread current) { 499 /* 500 * This code is in part redundant with that in 501 * tryAcquireShared but is simpler overall by not 502 * complicating tryAcquireShared with interactions between 503 * retries and lazily reading hold counts. 504 */ 505 HoldCounter rh = null; 506 for (;;) { 507 int c = getState(); 508 if (exclusiveCount(c) != 0) { 509 if (getExclusiveOwnerThread() != current) 510 return -1; 511 // else we hold the exclusive lock; blocking here 512 // would cause deadlock. 513 } else if (readerShouldBlock()) { 514 // Make sure we're not acquiring read lock reentrantly 515 if (firstReader == current) { 516 // assert firstReaderHoldCount > 0; 517 } else { 518 if (rh == null) { 519 rh = cachedHoldCounter; 520 if (rh == null || rh.tid != current.getId()) { 521 rh = readHolds.get(); 522 if (rh.count == 0) 523 readHolds.remove(); 524 } 525 } 526 if (rh.count == 0) 527 return -1; 528 } 529 } 530 if (sharedCount(c) == MAX_COUNT) 531 throw new Error("Maximum lock count exceeded"); 532 if (compareAndSetState(c, c + SHARED_UNIT)) { 533 if (sharedCount(c) == 0) { 534 firstReader = current; 535 firstReaderHoldCount = 1; 536 } else if (firstReader == current) { 537 firstReaderHoldCount++; 538 } else { 539 if (rh == null) 540 rh = cachedHoldCounter; 541 if (rh == null || rh.tid != current.getId()) 542 rh = readHolds.get(); 543 else if (rh.count == 0) 544 readHolds.set(rh); 545 rh.count++; 546 cachedHoldCounter = rh; // cache for release 547 } 548 return 1; 549 } 550 } 551 } 552 553 /** 554 * Performs tryLock for write, enabling barging in both modes. 555 * This is identical in effect to tryAcquire except for lack 556 * of calls to writerShouldBlock. 557 */ 558 final boolean tryWriteLock() { 559 Thread current = Thread.currentThread(); 560 int c = getState(); 561 if (c != 0) { 562 int w = exclusiveCount(c); 563 if (w == 0 || current != getExclusiveOwnerThread()) 564 return false; 565 if (w == MAX_COUNT) 566 throw new Error("Maximum lock count exceeded"); 567 } 568 if (!compareAndSetState(c, c + 1)) 569 return false; 570 setExclusiveOwnerThread(current); 571 return true; 572 } 573 574 /** 575 * Performs tryLock for read, enabling barging in both modes. 576 * This is identical in effect to tryAcquireShared except for 577 * lack of calls to readerShouldBlock. 578 */ 579 final boolean tryReadLock() { 580 Thread current = Thread.currentThread(); 581 for (;;) { 582 int c = getState(); 583 if (exclusiveCount(c) != 0 && 584 getExclusiveOwnerThread() != current) 585 return false; 586 int r = sharedCount(c); 587 if (r == MAX_COUNT) 588 throw new Error("Maximum lock count exceeded"); 589 if (compareAndSetState(c, c + SHARED_UNIT)) { 590 if (r == 0) { 591 firstReader = current; 592 firstReaderHoldCount = 1; 593 } else if (firstReader == current) { 594 firstReaderHoldCount++; 595 } else { 596 HoldCounter rh = cachedHoldCounter; 597 if (rh == null || rh.tid != current.getId()) 598 cachedHoldCounter = rh = readHolds.get(); 599 else if (rh.count == 0) 600 readHolds.set(rh); 601 rh.count++; 602 } 603 return true; 604 } 605 } 606 } 607 608 protected final boolean isHeldExclusively() { 609 // While we must in general read state before owner, 610 // we don't need to do so to check if current thread is owner 611 return getExclusiveOwnerThread() == Thread.currentThread(); 612 } 613 614 // Methods relayed to outer class 615 616 final ConditionObject newCondition() { 617 return new ConditionObject(); 618 } 619 620 final Thread getOwner() { 621 // Must read state before owner to ensure memory consistency 622 return ((exclusiveCount(getState()) == 0) ? 623 null : 624 getExclusiveOwnerThread()); 625 } 626 627 final int getReadLockCount() { 628 return sharedCount(getState()); 629 } 630 631 final boolean isWriteLocked() { 632 return exclusiveCount(getState()) != 0; 633 } 634 635 final int getWriteHoldCount() { 636 return isHeldExclusively() ? exclusiveCount(getState()) : 0; 637 } 638 639 final int getReadHoldCount() { 640 if (getReadLockCount() == 0) 641 return 0; 642 643 Thread current = Thread.currentThread(); 644 if (firstReader == current) 645 return firstReaderHoldCount; 646 647 HoldCounter rh = cachedHoldCounter; 648 if (rh != null && rh.tid == current.getId()) 649 return rh.count; 650 651 int count = readHolds.get().count; 652 if (count == 0) readHolds.remove(); 653 return count; 654 } 655 656 /** 657 * Reconstitute this lock instance from a stream 658 * @param s the stream 659 */ 660 private void readObject(java.io.ObjectInputStream s) 661 throws java.io.IOException, ClassNotFoundException { 662 s.defaultReadObject(); 663 readHolds = new ThreadLocalHoldCounter(); 664 setState(0); // reset to unlocked state 665 } 666 667 final int getCount() { return getState(); } 668 } 669 670 /** 671 * Nonfair version of Sync 672 */ 673 static final class NonfairSync extends Sync { 674 private static final long serialVersionUID = -8159625535654395037L; 675 final boolean writerShouldBlock() { 676 return false; // writers can always barge 677 } 678 final boolean readerShouldBlock() { 679 /* As a heuristic to avoid indefinite writer starvation, 680 * block if the thread that momentarily appears to be head 681 * of queue, if one exists, is a waiting writer. This is 682 * only a probabilistic effect since a new reader will not 683 * block if there is a waiting writer behind other enabled 684 * readers that have not yet drained from the queue. 685 */ 686 return apparentlyFirstQueuedIsExclusive(); 687 } 688 } 689 690 /** 691 * Fair version of Sync 692 */ 693 static final class FairSync extends Sync { 694 private static final long serialVersionUID = -2274990926593161451L; 695 final boolean writerShouldBlock() { 696 return hasQueuedPredecessors(); 697 } 698 final boolean readerShouldBlock() { 699 return hasQueuedPredecessors(); 700 } 701 } 702 703 /** 704 * The lock returned by method {@link ReentrantReadWriteLock#readLock}. 705 */ 706 public static class ReadLock implements Lock, java.io.Serializable { 707 private static final long serialVersionUID = -5992448646407690164L; 708 private final Sync sync; 709 710 /** 711 * Constructor for use by subclasses 712 * 713 * @param lock the outer lock object 714 * @throws NullPointerException if the lock is null 715 */ 716 protected ReadLock(ReentrantReadWriteLock lock) { 717 sync = lock.sync; 718 } 719 720 /** 721 * Acquires the read lock. 722 * 723 * <p>Acquires the read lock if the write lock is not held by 724 * another thread and returns immediately. 725 * 726 * <p>If the write lock is held by another thread then 727 * the current thread becomes disabled for thread scheduling 728 * purposes and lies dormant until the read lock has been acquired. 729 */ 730 public void lock() { 731 sync.acquireShared(1); 732 } 733 734 /** 735 * Acquires the read lock unless the current thread is 736 * {@linkplain Thread#interrupt interrupted}. 737 * 738 * <p>Acquires the read lock if the write lock is not held 739 * by another thread and returns immediately. 740 * 741 * <p>If the write lock is held by another thread then the 742 * current thread becomes disabled for thread scheduling 743 * purposes and lies dormant until one of two things happens: 744 * 745 * <ul> 746 * 747 * <li>The read lock is acquired by the current thread; or 748 * 749 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 750 * the current thread. 751 * 752 * </ul> 753 * 754 * <p>If the current thread: 755 * 756 * <ul> 757 * 758 * <li>has its interrupted status set on entry to this method; or 759 * 760 * <li>is {@linkplain Thread#interrupt interrupted} while 761 * acquiring the read lock, 762 * 763 * </ul> 764 * 765 * then {@link InterruptedException} is thrown and the current 766 * thread's interrupted status is cleared. 767 * 768 * <p>In this implementation, as this method is an explicit 769 * interruption point, preference is given to responding to 770 * the interrupt over normal or reentrant acquisition of the 771 * lock. 772 * 773 * @throws InterruptedException if the current thread is interrupted 774 */ 775 public void lockInterruptibly() throws InterruptedException { 776 sync.acquireSharedInterruptibly(1); 777 } 778 779 /** 780 * Acquires the read lock only if the write lock is not held by 781 * another thread at the time of invocation. 782 * 783 * <p>Acquires the read lock if the write lock is not held by 784 * another thread and returns immediately with the value 785 * {@code true}. Even when this lock has been set to use a 786 * fair ordering policy, a call to {@code tryLock()} 787 * <em>will</em> immediately acquire the read lock if it is 788 * available, whether or not other threads are currently 789 * waiting for the read lock. This "barging" behavior 790 * can be useful in certain circumstances, even though it 791 * breaks fairness. If you want to honor the fairness setting 792 * for this lock, then use {@link #tryLock(long, TimeUnit) 793 * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent 794 * (it also detects interruption). 795 * 796 * <p>If the write lock is held by another thread then 797 * this method will return immediately with the value 798 * {@code false}. 799 * 800 * @return {@code true} if the read lock was acquired 801 */ 802 public boolean tryLock() { 803 return sync.tryReadLock(); 804 } 805 806 /** 807 * Acquires the read lock if the write lock is not held by 808 * another thread within the given waiting time and the 809 * current thread has not been {@linkplain Thread#interrupt 810 * interrupted}. 811 * 812 * <p>Acquires the read lock if the write lock is not held by 813 * another thread and returns immediately with the value 814 * {@code true}. If this lock has been set to use a fair 815 * ordering policy then an available lock <em>will not</em> be 816 * acquired if any other threads are waiting for the 817 * lock. This is in contrast to the {@link #tryLock()} 818 * method. If you want a timed {@code tryLock} that does 819 * permit barging on a fair lock then combine the timed and 820 * un-timed forms together: 821 * 822 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } 823 * </pre> 824 * 825 * <p>If the write lock is held by another thread then the 826 * current thread becomes disabled for thread scheduling 827 * purposes and lies dormant until one of three things happens: 828 * 829 * <ul> 830 * 831 * <li>The read lock is acquired by the current thread; or 832 * 833 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 834 * the current thread; or 835 * 836 * <li>The specified waiting time elapses. 837 * 838 * </ul> 839 * 840 * <p>If the read lock is acquired then the value {@code true} is 841 * returned. 842 * 843 * <p>If the current thread: 844 * 845 * <ul> 846 * 847 * <li>has its interrupted status set on entry to this method; or 848 * 849 * <li>is {@linkplain Thread#interrupt interrupted} while 850 * acquiring the read lock, 851 * 852 * </ul> then {@link InterruptedException} is thrown and the 853 * current thread's interrupted status is cleared. 854 * 855 * <p>If the specified waiting time elapses then the value 856 * {@code false} is returned. If the time is less than or 857 * equal to zero, the method will not wait at all. 858 * 859 * <p>In this implementation, as this method is an explicit 860 * interruption point, preference is given to responding to 861 * the interrupt over normal or reentrant acquisition of the 862 * lock, and over reporting the elapse of the waiting time. 863 * 864 * @param timeout the time to wait for the read lock 865 * @param unit the time unit of the timeout argument 866 * @return {@code true} if the read lock was acquired 867 * @throws InterruptedException if the current thread is interrupted 868 * @throws NullPointerException if the time unit is null 869 * 870 */ 871 public boolean tryLock(long timeout, TimeUnit unit) 872 throws InterruptedException { 873 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 874 } 875 876 /** 877 * Attempts to release this lock. 878 * 879 * <p> If the number of readers is now zero then the lock 880 * is made available for write lock attempts. 881 */ 882 public void unlock() { 883 sync.releaseShared(1); 884 } 885 886 /** 887 * Throws {@code UnsupportedOperationException} because 888 * {@code ReadLocks} do not support conditions. 889 * 890 * @throws UnsupportedOperationException always 891 */ 892 public Condition newCondition() { 893 throw new UnsupportedOperationException(); 894 } 895 896 /** 897 * Returns a string identifying this lock, as well as its lock state. 898 * The state, in brackets, includes the String {@code "Read locks ="} 899 * followed by the number of held read locks. 900 * 901 * @return a string identifying this lock, as well as its lock state 902 */ 903 public String toString() { 904 int r = sync.getReadLockCount(); 905 return super.toString() + 906 "[Read locks = " + r + "]"; 907 } 908 } 909 910 /** 911 * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. 912 */ 913 public static class WriteLock implements Lock, java.io.Serializable { 914 private static final long serialVersionUID = -4992448646407690164L; 915 private final Sync sync; 916 917 /** 918 * Constructor for use by subclasses 919 * 920 * @param lock the outer lock object 921 * @throws NullPointerException if the lock is null 922 */ 923 protected WriteLock(ReentrantReadWriteLock lock) { 924 sync = lock.sync; 925 } 926 927 /** 928 * Acquires the write lock. 929 * 930 * <p>Acquires the write lock if neither the read nor write lock 931 * are held by another thread 932 * and returns immediately, setting the write lock hold count to 933 * one. 934 * 935 * <p>If the current thread already holds the write lock then the 936 * hold count is incremented by one and the method returns 937 * immediately. 938 * 939 * <p>If the lock is held by another thread then the current 940 * thread becomes disabled for thread scheduling purposes and 941 * lies dormant until the write lock has been acquired, at which 942 * time the write lock hold count is set to one. 943 */ 944 public void lock() { 945 sync.acquire(1); 946 } 947 948 /** 949 * Acquires the write lock unless the current thread is 950 * {@linkplain Thread#interrupt interrupted}. 951 * 952 * <p>Acquires the write lock if neither the read nor write lock 953 * are held by another thread 954 * and returns immediately, setting the write lock hold count to 955 * one. 956 * 957 * <p>If the current thread already holds this lock then the 958 * hold count is incremented by one and the method returns 959 * immediately. 960 * 961 * <p>If the lock is held by another thread then the current 962 * thread becomes disabled for thread scheduling purposes and 963 * lies dormant until one of two things happens: 964 * 965 * <ul> 966 * 967 * <li>The write lock is acquired by the current thread; or 968 * 969 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 970 * the current thread. 971 * 972 * </ul> 973 * 974 * <p>If the write lock is acquired by the current thread then the 975 * lock hold count is set to one. 976 * 977 * <p>If the current thread: 978 * 979 * <ul> 980 * 981 * <li>has its interrupted status set on entry to this method; 982 * or 983 * 984 * <li>is {@linkplain Thread#interrupt interrupted} while 985 * acquiring the write lock, 986 * 987 * </ul> 988 * 989 * then {@link InterruptedException} is thrown and the current 990 * thread's interrupted status is cleared. 991 * 992 * <p>In this implementation, as this method is an explicit 993 * interruption point, preference is given to responding to 994 * the interrupt over normal or reentrant acquisition of the 995 * lock. 996 * 997 * @throws InterruptedException if the current thread is interrupted 998 */ 999 public void lockInterruptibly() throws InterruptedException { 1000 sync.acquireInterruptibly(1); 1001 } 1002 1003 /** 1004 * Acquires the write lock only if it is not held by another thread 1005 * at the time of invocation. 1006 * 1007 * <p>Acquires the write lock if neither the read nor write lock 1008 * are held by another thread 1009 * and returns immediately with the value {@code true}, 1010 * setting the write lock hold count to one. Even when this lock has 1011 * been set to use a fair ordering policy, a call to 1012 * {@code tryLock()} <em>will</em> immediately acquire the 1013 * lock if it is available, whether or not other threads are 1014 * currently waiting for the write lock. This "barging" 1015 * behavior can be useful in certain circumstances, even 1016 * though it breaks fairness. If you want to honor the 1017 * fairness setting for this lock, then use {@link 1018 * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } 1019 * which is almost equivalent (it also detects interruption). 1020 * 1021 * <p> If the current thread already holds this lock then the 1022 * hold count is incremented by one and the method returns 1023 * {@code true}. 1024 * 1025 * <p>If the lock is held by another thread then this method 1026 * will return immediately with the value {@code false}. 1027 * 1028 * @return {@code true} if the lock was free and was acquired 1029 * by the current thread, or the write lock was already held 1030 * by the current thread; and {@code false} otherwise. 1031 */ 1032 public boolean tryLock( ) { 1033 return sync.tryWriteLock(); 1034 } 1035 1036 /** 1037 * Acquires the write lock if it is not held by another thread 1038 * within the given waiting time and the current thread has 1039 * not been {@linkplain Thread#interrupt interrupted}. 1040 * 1041 * <p>Acquires the write lock if neither the read nor write lock 1042 * are held by another thread 1043 * and returns immediately with the value {@code true}, 1044 * setting the write lock hold count to one. If this lock has been 1045 * set to use a fair ordering policy then an available lock 1046 * <em>will not</em> be acquired if any other threads are 1047 * waiting for the write lock. This is in contrast to the {@link 1048 * #tryLock()} method. If you want a timed {@code tryLock} 1049 * that does permit barging on a fair lock then combine the 1050 * timed and un-timed forms together: 1051 * 1052 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } 1053 * </pre> 1054 * 1055 * <p>If the current thread already holds this lock then the 1056 * hold count is incremented by one and the method returns 1057 * {@code true}. 1058 * 1059 * <p>If the lock is held by another thread then the current 1060 * thread becomes disabled for thread scheduling purposes and 1061 * lies dormant until one of three things happens: 1062 * 1063 * <ul> 1064 * 1065 * <li>The write lock is acquired by the current thread; or 1066 * 1067 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 1068 * the current thread; or 1069 * 1070 * <li>The specified waiting time elapses 1071 * 1072 * </ul> 1073 * 1074 * <p>If the write lock is acquired then the value {@code true} is 1075 * returned and the write lock hold count is set to one. 1076 * 1077 * <p>If the current thread: 1078 * 1079 * <ul> 1080 * 1081 * <li>has its interrupted status set on entry to this method; 1082 * or 1083 * 1084 * <li>is {@linkplain Thread#interrupt interrupted} while 1085 * acquiring the write lock, 1086 * 1087 * </ul> 1088 * 1089 * then {@link InterruptedException} is thrown and the current 1090 * thread's interrupted status is cleared. 1091 * 1092 * <p>If the specified waiting time elapses then the value 1093 * {@code false} is returned. If the time is less than or 1094 * equal to zero, the method will not wait at all. 1095 * 1096 * <p>In this implementation, as this method is an explicit 1097 * interruption point, preference is given to responding to 1098 * the interrupt over normal or reentrant acquisition of the 1099 * lock, and over reporting the elapse of the waiting time. 1100 * 1101 * @param timeout the time to wait for the write lock 1102 * @param unit the time unit of the timeout argument 1103 * 1104 * @return {@code true} if the lock was free and was acquired 1105 * by the current thread, or the write lock was already held by the 1106 * current thread; and {@code false} if the waiting time 1107 * elapsed before the lock could be acquired. 1108 * 1109 * @throws InterruptedException if the current thread is interrupted 1110 * @throws NullPointerException if the time unit is null 1111 * 1112 */ 1113 public boolean tryLock(long timeout, TimeUnit unit) 1114 throws InterruptedException { 1115 return sync.tryAcquireNanos(1, unit.toNanos(timeout)); 1116 } 1117 1118 /** 1119 * Attempts to release this lock. 1120 * 1121 * <p>If the current thread is the holder of this lock then 1122 * the hold count is decremented. If the hold count is now 1123 * zero then the lock is released. If the current thread is 1124 * not the holder of this lock then {@link 1125 * IllegalMonitorStateException} is thrown. 1126 * 1127 * @throws IllegalMonitorStateException if the current thread does not 1128 * hold this lock. 1129 */ 1130 public void unlock() { 1131 sync.release(1); 1132 } 1133 1134 /** 1135 * Returns a {@link Condition} instance for use with this 1136 * {@link Lock} instance. 1137 * <p>The returned {@link Condition} instance supports the same 1138 * usages as do the {@link Object} monitor methods ({@link 1139 * Object#wait() wait}, {@link Object#notify notify}, and {@link 1140 * Object#notifyAll notifyAll}) when used with the built-in 1141 * monitor lock. 1142 * 1143 * <ul> 1144 * 1145 * <li>If this write lock is not held when any {@link 1146 * Condition} method is called then an {@link 1147 * IllegalMonitorStateException} is thrown. (Read locks are 1148 * held independently of write locks, so are not checked or 1149 * affected. However it is essentially always an error to 1150 * invoke a condition waiting method when the current thread 1151 * has also acquired read locks, since other threads that 1152 * could unblock it will not be able to acquire the write 1153 * lock.) 1154 * 1155 * <li>When the condition {@linkplain Condition#await() waiting} 1156 * methods are called the write lock is released and, before 1157 * they return, the write lock is reacquired and the lock hold 1158 * count restored to what it was when the method was called. 1159 * 1160 * <li>If a thread is {@linkplain Thread#interrupt interrupted} while 1161 * waiting then the wait will terminate, an {@link 1162 * InterruptedException} will be thrown, and the thread's 1163 * interrupted status will be cleared. 1164 * 1165 * <li> Waiting threads are signalled in FIFO order. 1166 * 1167 * <li>The ordering of lock reacquisition for threads returning 1168 * from waiting methods is the same as for threads initially 1169 * acquiring the lock, which is in the default case not specified, 1170 * but for <em>fair</em> locks favors those threads that have been 1171 * waiting the longest. 1172 * 1173 * </ul> 1174 * 1175 * @return the Condition object 1176 */ 1177 public Condition newCondition() { 1178 return sync.newCondition(); 1179 } 1180 1181 /** 1182 * Returns a string identifying this lock, as well as its lock 1183 * state. The state, in brackets includes either the String 1184 * {@code "Unlocked"} or the String {@code "Locked by"} 1185 * followed by the {@linkplain Thread#getName name} of the owning thread. 1186 * 1187 * @return a string identifying this lock, as well as its lock state 1188 */ 1189 public String toString() { 1190 Thread o = sync.getOwner(); 1191 return super.toString() + ((o == null) ? 1192 "[Unlocked]" : 1193 "[Locked by thread " + o.getName() + "]"); 1194 } 1195 1196 /** 1197 * Queries if this write lock is held by the current thread. 1198 * Identical in effect to {@link 1199 * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. 1200 * 1201 * @return {@code true} if the current thread holds this lock and 1202 * {@code false} otherwise 1203 * @since 1.6 1204 */ 1205 public boolean isHeldByCurrentThread() { 1206 return sync.isHeldExclusively(); 1207 } 1208 1209 /** 1210 * Queries the number of holds on this write lock by the current 1211 * thread. A thread has a hold on a lock for each lock action 1212 * that is not matched by an unlock action. Identical in effect 1213 * to {@link ReentrantReadWriteLock#getWriteHoldCount}. 1214 * 1215 * @return the number of holds on this lock by the current thread, 1216 * or zero if this lock is not held by the current thread 1217 * @since 1.6 1218 */ 1219 public int getHoldCount() { 1220 return sync.getWriteHoldCount(); 1221 } 1222 } 1223 1224 // Instrumentation and status 1225 1226 /** 1227 * Returns {@code true} if this lock has fairness set true. 1228 * 1229 * @return {@code true} if this lock has fairness set true 1230 */ 1231 public final boolean isFair() { 1232 return sync instanceof FairSync; 1233 } 1234 1235 /** 1236 * Returns the thread that currently owns the write lock, or 1237 * {@code null} if not owned. When this method is called by a 1238 * thread that is not the owner, the return value reflects a 1239 * best-effort approximation of current lock status. For example, 1240 * the owner may be momentarily {@code null} even if there are 1241 * threads trying to acquire the lock but have not yet done so. 1242 * This method is designed to facilitate construction of 1243 * subclasses that provide more extensive lock monitoring 1244 * facilities. 1245 * 1246 * @return the owner, or {@code null} if not owned 1247 */ 1248 protected Thread getOwner() { 1249 return sync.getOwner(); 1250 } 1251 1252 /** 1253 * Queries the number of read locks held for this lock. This 1254 * method is designed for use in monitoring system state, not for 1255 * synchronization control. 1256 * @return the number of read locks held. 1257 */ 1258 public int getReadLockCount() { 1259 return sync.getReadLockCount(); 1260 } 1261 1262 /** 1263 * Queries if the write lock is held by any thread. This method is 1264 * designed for use in monitoring system state, not for 1265 * synchronization control. 1266 * 1267 * @return {@code true} if any thread holds the write lock and 1268 * {@code false} otherwise 1269 */ 1270 public boolean isWriteLocked() { 1271 return sync.isWriteLocked(); 1272 } 1273 1274 /** 1275 * Queries if the write lock is held by the current thread. 1276 * 1277 * @return {@code true} if the current thread holds the write lock and 1278 * {@code false} otherwise 1279 */ 1280 public boolean isWriteLockedByCurrentThread() { 1281 return sync.isHeldExclusively(); 1282 } 1283 1284 /** 1285 * Queries the number of reentrant write holds on this lock by the 1286 * current thread. A writer thread has a hold on a lock for 1287 * each lock action that is not matched by an unlock action. 1288 * 1289 * @return the number of holds on the write lock by the current thread, 1290 * or zero if the write lock is not held by the current thread 1291 */ 1292 public int getWriteHoldCount() { 1293 return sync.getWriteHoldCount(); 1294 } 1295 1296 /** 1297 * Queries the number of reentrant read holds on this lock by the 1298 * current thread. A reader thread has a hold on a lock for 1299 * each lock action that is not matched by an unlock action. 1300 * 1301 * @return the number of holds on the read lock by the current thread, 1302 * or zero if the read lock is not held by the current thread 1303 * @since 1.6 1304 */ 1305 public int getReadHoldCount() { 1306 return sync.getReadHoldCount(); 1307 } 1308 1309 /** 1310 * Returns a collection containing threads that may be waiting to 1311 * acquire the write lock. Because the actual set of threads may 1312 * change dynamically while constructing this result, the returned 1313 * collection is only a best-effort estimate. The elements of the 1314 * returned collection are in no particular order. This method is 1315 * designed to facilitate construction of subclasses that provide 1316 * more extensive lock monitoring facilities. 1317 * 1318 * @return the collection of threads 1319 */ 1320 protected Collection<Thread> getQueuedWriterThreads() { 1321 return sync.getExclusiveQueuedThreads(); 1322 } 1323 1324 /** 1325 * Returns a collection containing threads that may be waiting to 1326 * acquire the read lock. Because the actual set of threads may 1327 * change dynamically while constructing this result, the returned 1328 * collection is only a best-effort estimate. The elements of the 1329 * returned collection are in no particular order. This method is 1330 * designed to facilitate construction of subclasses that provide 1331 * more extensive lock monitoring facilities. 1332 * 1333 * @return the collection of threads 1334 */ 1335 protected Collection<Thread> getQueuedReaderThreads() { 1336 return sync.getSharedQueuedThreads(); 1337 } 1338 1339 /** 1340 * Queries whether any threads are waiting to acquire the read or 1341 * write lock. Note that because cancellations may occur at any 1342 * time, a {@code true} return does not guarantee that any other 1343 * thread will ever acquire a lock. This method is designed 1344 * primarily for use in monitoring of the system state. 1345 * 1346 * @return {@code true} if there may be other threads waiting to 1347 * acquire the lock 1348 */ 1349 public final boolean hasQueuedThreads() { 1350 return sync.hasQueuedThreads(); 1351 } 1352 1353 /** 1354 * Queries whether the given thread is waiting to acquire either 1355 * the read or write lock. Note that because cancellations may 1356 * occur at any time, a {@code true} return does not guarantee 1357 * that this thread will ever acquire a lock. This method is 1358 * designed primarily for use in monitoring of the system state. 1359 * 1360 * @param thread the thread 1361 * @return {@code true} if the given thread is queued waiting for this lock 1362 * @throws NullPointerException if the thread is null 1363 */ 1364 public final boolean hasQueuedThread(Thread thread) { 1365 return sync.isQueued(thread); 1366 } 1367 1368 /** 1369 * Returns an estimate of the number of threads waiting to acquire 1370 * either the read or write lock. The value is only an estimate 1371 * because the number of threads may change dynamically while this 1372 * method traverses internal data structures. This method is 1373 * designed for use in monitoring of the system state, not for 1374 * synchronization control. 1375 * 1376 * @return the estimated number of threads waiting for this lock 1377 */ 1378 public final int getQueueLength() { 1379 return sync.getQueueLength(); 1380 } 1381 1382 /** 1383 * Returns a collection containing threads that may be waiting to 1384 * acquire either the read or write lock. Because the actual set 1385 * of threads may change dynamically while constructing this 1386 * result, the returned collection is only a best-effort estimate. 1387 * The elements of the returned collection are in no particular 1388 * order. This method is designed to facilitate construction of 1389 * subclasses that provide more extensive monitoring facilities. 1390 * 1391 * @return the collection of threads 1392 */ 1393 protected Collection<Thread> getQueuedThreads() { 1394 return sync.getQueuedThreads(); 1395 } 1396 1397 /** 1398 * Queries whether any threads are waiting on the given condition 1399 * associated with the write lock. Note that because timeouts and 1400 * interrupts may occur at any time, a {@code true} return does 1401 * not guarantee that a future {@code signal} will awaken any 1402 * threads. This method is designed primarily for use in 1403 * monitoring of the system state. 1404 * 1405 * @param condition the condition 1406 * @return {@code true} if there are any waiting threads 1407 * @throws IllegalMonitorStateException if this lock is not held 1408 * @throws IllegalArgumentException if the given condition is 1409 * not associated with this lock 1410 * @throws NullPointerException if the condition is null 1411 */ 1412 public boolean hasWaiters(Condition condition) { 1413 if (condition == null) 1414 throw new NullPointerException(); 1415 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1416 throw new IllegalArgumentException("not owner"); 1417 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); 1418 } 1419 1420 /** 1421 * Returns an estimate of the number of threads waiting on the 1422 * given condition associated with the write lock. Note that because 1423 * timeouts and interrupts may occur at any time, the estimate 1424 * serves only as an upper bound on the actual number of waiters. 1425 * This method is designed for use in monitoring of the system 1426 * state, not for synchronization control. 1427 * 1428 * @param condition the condition 1429 * @return the estimated number of waiting threads 1430 * @throws IllegalMonitorStateException if this lock is not held 1431 * @throws IllegalArgumentException if the given condition is 1432 * not associated with this lock 1433 * @throws NullPointerException if the condition is null 1434 */ 1435 public int getWaitQueueLength(Condition condition) { 1436 if (condition == null) 1437 throw new NullPointerException(); 1438 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1439 throw new IllegalArgumentException("not owner"); 1440 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); 1441 } 1442 1443 /** 1444 * Returns a collection containing those threads that may be 1445 * waiting on the given condition associated with the write lock. 1446 * Because the actual set of threads may change dynamically while 1447 * constructing this result, the returned collection is only a 1448 * best-effort estimate. The elements of the returned collection 1449 * are in no particular order. This method is designed to 1450 * facilitate construction of subclasses that provide more 1451 * extensive condition monitoring facilities. 1452 * 1453 * @param condition the condition 1454 * @return the collection of threads 1455 * @throws IllegalMonitorStateException if this lock is not held 1456 * @throws IllegalArgumentException if the given condition is 1457 * not associated with this lock 1458 * @throws NullPointerException if the condition is null 1459 */ 1460 protected Collection<Thread> getWaitingThreads(Condition condition) { 1461 if (condition == null) 1462 throw new NullPointerException(); 1463 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1464 throw new IllegalArgumentException("not owner"); 1465 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); 1466 } 1467 1468 /** 1469 * Returns a string identifying this lock, as well as its lock state. 1470 * The state, in brackets, includes the String {@code "Write locks ="} 1471 * followed by the number of reentrantly held write locks, and the 1472 * String {@code "Read locks ="} followed by the number of held 1473 * read locks. 1474 * 1475 * @return a string identifying this lock, as well as its lock state 1476 */ 1477 public String toString() { 1478 int c = sync.getCount(); 1479 int w = Sync.exclusiveCount(c); 1480 int r = Sync.sharedCount(c); 1481 1482 return super.toString() + 1483 "[Write locks = " + w + ", Read locks = " + r + "]"; 1484 } 1485 1486 }
AQS的完整源码
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /* 2 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 */ 24 25 /* 26 * 27 * 28 * 29 * 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.locks; 37 import java.util.*; 38 import java.util.concurrent.*; 39 import java.util.concurrent.atomic.*; 40 import sun.misc.Unsafe; 41 42 /** 43 * Provides a framework for implementing blocking locks and related 44 * synchronizers (semaphores, events, etc) that rely on 45 * first-in-first-out (FIFO) wait queues. This class is designed to 46 * be a useful basis for most kinds of synchronizers that rely on a 47 * single atomic <tt>int</tt> value to represent state. Subclasses 48 * must define the protected methods that change this state, and which 49 * define what that state means in terms of this object being acquired 50 * or released. Given these, the other methods in this class carry 51 * out all queuing and blocking mechanics. Subclasses can maintain 52 * other state fields, but only the atomically updated <tt>int</tt> 53 * value manipulated using methods {@link #getState}, {@link 54 * #setState} and {@link #compareAndSetState} is tracked with respect 55 * to synchronization. 56 * 57 * <p>Subclasses should be defined as non-public internal helper 58 * classes that are used to implement the synchronization properties 59 * of their enclosing class. Class 60 * <tt>AbstractQueuedSynchronizer</tt> does not implement any 61 * synchronization interface. Instead it defines methods such as 62 * {@link #acquireInterruptibly} that can be invoked as 63 * appropriate by concrete locks and related synchronizers to 64 * implement their public methods. 65 * 66 * <p>This class supports either or both a default <em>exclusive</em> 67 * mode and a <em>shared</em> mode. When acquired in exclusive mode, 68 * attempted acquires by other threads cannot succeed. Shared mode 69 * acquires by multiple threads may (but need not) succeed. This class 70 * does not "understand" these differences except in the 71 * mechanical sense that when a shared mode acquire succeeds, the next 72 * waiting thread (if one exists) must also determine whether it can 73 * acquire as well. Threads waiting in the different modes share the 74 * same FIFO queue. Usually, implementation subclasses support only 75 * one of these modes, but both can come into play for example in a 76 * {@link ReadWriteLock}. Subclasses that support only exclusive or 77 * only shared modes need not define the methods supporting the unused mode. 78 * 79 * <p>This class defines a nested {@link ConditionObject} class that 80 * can be used as a {@link Condition} implementation by subclasses 81 * supporting exclusive mode for which method {@link 82 * #isHeldExclusively} reports whether synchronization is exclusively 83 * held with respect to the current thread, method {@link #release} 84 * invoked with the current {@link #getState} value fully releases 85 * this object, and {@link #acquire}, given this saved state value, 86 * eventually restores this object to its previous acquired state. No 87 * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a 88 * condition, so if this constraint cannot be met, do not use it. The 89 * behavior of {@link ConditionObject} depends of course on the 90 * semantics of its synchronizer implementation. 91 * 92 * <p>This class provides inspection, instrumentation, and monitoring 93 * methods for the internal queue, as well as similar methods for 94 * condition objects. These can be exported as desired into classes 95 * using an <tt>AbstractQueuedSynchronizer</tt> for their 96 * synchronization mechanics. 97 * 98 * <p>Serialization of this class stores only the underlying atomic 99 * integer maintaining state, so deserialized objects have empty 100 * thread queues. Typical subclasses requiring serializability will 101 * define a <tt>readObject</tt> method that restores this to a known 102 * initial state upon deserialization. 103 * 104 * <h3>Usage</h3> 105 * 106 * <p>To use this class as the basis of a synchronizer, redefine the 107 * following methods, as applicable, by inspecting and/or modifying 108 * the synchronization state using {@link #getState}, {@link 109 * #setState} and/or {@link #compareAndSetState}: 110 * 111 * <ul> 112 * <li> {@link #tryAcquire} 113 * <li> {@link #tryRelease} 114 * <li> {@link #tryAcquireShared} 115 * <li> {@link #tryReleaseShared} 116 * <li> {@link #isHeldExclusively} 117 *</ul> 118 * 119 * Each of these methods by default throws {@link 120 * UnsupportedOperationException}. Implementations of these methods 121 * must be internally thread-safe, and should in general be short and 122 * not block. Defining these methods is the <em>only</em> supported 123 * means of using this class. All other methods are declared 124 * <tt>final</tt> because they cannot be independently varied. 125 * 126 * <p>You may also find the inherited methods from {@link 127 * AbstractOwnableSynchronizer} useful to keep track of the thread 128 * owning an exclusive synchronizer. You are encouraged to use them 129 * -- this enables monitoring and diagnostic tools to assist users in 130 * determining which threads hold locks. 131 * 132 * <p>Even though this class is based on an internal FIFO queue, it 133 * does not automatically enforce FIFO acquisition policies. The core 134 * of exclusive synchronization takes the form: 135 * 136 * <pre> 137 * Acquire: 138 * while (!tryAcquire(arg)) { 139 * <em>enqueue thread if it is not already queued</em>; 140 * <em>possibly block current thread</em>; 141 * } 142 * 143 * Release: 144 * if (tryRelease(arg)) 145 * <em>unblock the first queued thread</em>; 146 * </pre> 147 * 148 * (Shared mode is similar but may involve cascading signals.) 149 * 150 * <p><a name="barging">Because checks in acquire are invoked before 151 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of 152 * others that are blocked and queued. However, you can, if desired, 153 * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to 154 * disable barging by internally invoking one or more of the inspection 155 * methods, thereby providing a <em>fair</em> FIFO acquisition order. 156 * In particular, most fair synchronizers can define <tt>tryAcquire</tt> 157 * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method 158 * specifically designed to be used by fair synchronizers) returns 159 * <tt>true</tt>. Other variations are possible. 160 * 161 * <p>Throughput and scalability are generally highest for the 162 * default barging (also known as <em>greedy</em>, 163 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy. 164 * While this is not guaranteed to be fair or starvation-free, earlier 165 * queued threads are allowed to recontend before later queued 166 * threads, and each recontention has an unbiased chance to succeed 167 * against incoming threads. Also, while acquires do not 168 * "spin" in the usual sense, they may perform multiple 169 * invocations of <tt>tryAcquire</tt> interspersed with other 170 * computations before blocking. This gives most of the benefits of 171 * spins when exclusive synchronization is only briefly held, without 172 * most of the liabilities when it isn't. If so desired, you can 173 * augment this by preceding calls to acquire methods with 174 * "fast-path" checks, possibly prechecking {@link #hasContended} 175 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer 176 * is likely not to be contended. 177 * 178 * <p>This class provides an efficient and scalable basis for 179 * synchronization in part by specializing its range of use to 180 * synchronizers that can rely on <tt>int</tt> state, acquire, and 181 * release parameters, and an internal FIFO wait queue. When this does 182 * not suffice, you can build synchronizers from a lower level using 183 * {@link java.util.concurrent.atomic atomic} classes, your own custom 184 * {@link java.util.Queue} classes, and {@link LockSupport} blocking 185 * support. 186 * 187 * <h3>Usage Examples</h3> 188 * 189 * <p>Here is a non-reentrant mutual exclusion lock class that uses 190 * the value zero to represent the unlocked state, and one to 191 * represent the locked state. While a non-reentrant lock 192 * does not strictly require recording of the current owner 193 * thread, this class does so anyway to make usage easier to monitor. 194 * It also supports conditions and exposes 195 * one of the instrumentation methods: 196 * 197 * <pre> 198 * class Mutex implements Lock, java.io.Serializable { 199 * 200 * // Our internal helper class 201 * private static class Sync extends AbstractQueuedSynchronizer { 202 * // Report whether in locked state 203 * protected boolean isHeldExclusively() { 204 * return getState() == 1; 205 * } 206 * 207 * // Acquire the lock if state is zero 208 * public boolean tryAcquire(int acquires) { 209 * assert acquires == 1; // Otherwise unused 210 * if (compareAndSetState(0, 1)) { 211 * setExclusiveOwnerThread(Thread.currentThread()); 212 * return true; 213 * } 214 * return false; 215 * } 216 * 217 * // Release the lock by setting state to zero 218 * protected boolean tryRelease(int releases) { 219 * assert releases == 1; // Otherwise unused 220 * if (getState() == 0) throw new IllegalMonitorStateException(); 221 * setExclusiveOwnerThread(null); 222 * setState(0); 223 * return true; 224 * } 225 * 226 * // Provide a Condition 227 * Condition newCondition() { return new ConditionObject(); } 228 * 229 * // Deserialize properly 230 * private void readObject(ObjectInputStream s) 231 * throws IOException, ClassNotFoundException { 232 * s.defaultReadObject(); 233 * setState(0); // reset to unlocked state 234 * } 235 * } 236 * 237 * // The sync object does all the hard work. We just forward to it. 238 * private final Sync sync = new Sync(); 239 * 240 * public void lock() { sync.acquire(1); } 241 * public boolean tryLock() { return sync.tryAcquire(1); } 242 * public void unlock() { sync.release(1); } 243 * public Condition newCondition() { return sync.newCondition(); } 244 * public boolean isLocked() { return sync.isHeldExclusively(); } 245 * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } 246 * public void lockInterruptibly() throws InterruptedException { 247 * sync.acquireInterruptibly(1); 248 * } 249 * public boolean tryLock(long timeout, TimeUnit unit) 250 * throws InterruptedException { 251 * return sync.tryAcquireNanos(1, unit.toNanos(timeout)); 252 * } 253 * } 254 * </pre> 255 * 256 * <p>Here is a latch class that is like a {@link CountDownLatch} 257 * except that it only requires a single <tt>signal</tt> to 258 * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt> 259 * acquire and release methods. 260 * 261 * <pre> 262 * class BooleanLatch { 263 * 264 * private static class Sync extends AbstractQueuedSynchronizer { 265 * boolean isSignalled() { return getState() != 0; } 266 * 267 * protected int tryAcquireShared(int ignore) { 268 * return isSignalled() ? 1 : -1; 269 * } 270 * 271 * protected boolean tryReleaseShared(int ignore) { 272 * setState(1); 273 * return true; 274 * } 275 * } 276 * 277 * private final Sync sync = new Sync(); 278 * public boolean isSignalled() { return sync.isSignalled(); } 279 * public void signal() { sync.releaseShared(1); } 280 * public void await() throws InterruptedException { 281 * sync.acquireSharedInterruptibly(1); 282 * } 283 * } 284 * </pre> 285 * 286 * @since 1.5 287 * @author Doug Lea 288 */ 289 public abstract class AbstractQueuedSynchronizer 290 extends AbstractOwnableSynchronizer 291 implements java.io.Serializable { 292 293 private static final long serialVersionUID = 7373984972572414691L; 294 295 /** 296 * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance 297 * with initial synchronization state of zero. 298 */ 299 protected AbstractQueuedSynchronizer() { } 300 301 /** 302 * Wait queue node class. 303 * 304 * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and 305 * Hagersten) lock queue. CLH locks are normally used for 306 * spinlocks. We instead use them for blocking synchronizers, but 307 * use the same basic tactic of holding some of the control 308 * information about a thread in the predecessor of its node. A 309 * "status" field in each node keeps track of whether a thread 310 * should block. A node is signalled when its predecessor 311 * releases. Each node of the queue otherwise serves as a 312 * specific-notification-style monitor holding a single waiting 313 * thread. The status field does NOT control whether threads are 314 * granted locks etc though. A thread may try to acquire if it is 315 * first in the queue. But being first does not guarantee success; 316 * it only gives the right to contend. So the currently released 317 * contender thread may need to rewait. 318 * 319 * <p>To enqueue into a CLH lock, you atomically splice it in as new 320 * tail. To dequeue, you just set the head field. 321 * <pre> 322 * +------+ prev +-----+ +-----+ 323 * head | | <---- | | <---- | | tail 324 * +------+ +-----+ +-----+ 325 * </pre> 326 * 327 * <p>Insertion into a CLH queue requires only a single atomic 328 * operation on "tail", so there is a simple atomic point of 329 * demarcation from unqueued to queued. Similarly, dequeing 330 * involves only updating the "head". However, it takes a bit 331 * more work for nodes to determine who their successors are, 332 * in part to deal with possible cancellation due to timeouts 333 * and interrupts. 334 * 335 * <p>The "prev" links (not used in original CLH locks), are mainly 336 * needed to handle cancellation. If a node is cancelled, its 337 * successor is (normally) relinked to a non-cancelled 338 * predecessor. For explanation of similar mechanics in the case 339 * of spin locks, see the papers by Scott and Scherer at 340 * http://www.cs.rochester.edu/u/scott/synchronization/ 341 * 342 * <p>We also use "next" links to implement blocking mechanics. 343 * The thread id for each node is kept in its own node, so a 344 * predecessor signals the next node to wake up by traversing 345 * next link to determine which thread it is. Determination of 346 * successor must avoid races with newly queued nodes to set 347 * the "next" fields of their predecessors. This is solved 348 * when necessary by checking backwards from the atomically 349 * updated "tail" when a node's successor appears to be null. 350 * (Or, said differently, the next-links are an optimization 351 * so that we don't usually need a backward scan.) 352 * 353 * <p>Cancellation introduces some conservatism to the basic 354 * algorithms. Since we must poll for cancellation of other 355 * nodes, we can miss noticing whether a cancelled node is 356 * ahead or behind us. This is dealt with by always unparking 357 * successors upon cancellation, allowing them to stabilize on 358 * a new predecessor, unless we can identify an uncancelled 359 * predecessor who will carry this responsibility. 360 * 361 * <p>CLH queues need a dummy header node to get started. But 362 * we don't create them on construction, because it would be wasted 363 * effort if there is never contention. Instead, the node 364 * is constructed and head and tail pointers are set upon first 365 * contention. 366 * 367 * <p>Threads waiting on Conditions use the same nodes, but 368 * use an additional link. Conditions only need to link nodes 369 * in simple (non-concurrent) linked queues because they are 370 * only accessed when exclusively held. Upon await, a node is 371 * inserted into a condition queue. Upon signal, the node is 372 * transferred to the main queue. A special value of status 373 * field is used to mark which queue a node is on. 374 * 375 * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill 376 * Scherer and Michael Scott, along with members of JSR-166 377 * expert group, for helpful ideas, discussions, and critiques 378 * on the design of this class. 379 */ 380 static final class Node { 381 /** Marker to indicate a node is waiting in shared mode */ 382 static final Node SHARED = new Node(); 383 /** Marker to indicate a node is waiting in exclusive mode */ 384 static final Node EXCLUSIVE = null; 385 386 /** waitStatus value to indicate thread has cancelled */ 387 static final int CANCELLED = 1; 388 /** waitStatus value to indicate successor's thread needs unparking */ 389 static final int SIGNAL = -1; 390 /** waitStatus value to indicate thread is waiting on condition */ 391 static final int CONDITION = -2; 392 /** 393 * waitStatus value to indicate the next acquireShared should 394 * unconditionally propagate 395 */ 396 static final int PROPAGATE = -3; 397 398 /** 399 * Status field, taking on only the values: 400 * SIGNAL: The successor of this node is (or will soon be) 401 * blocked (via park), so the current node must 402 * unpark its successor when it releases or 403 * cancels. To avoid races, acquire methods must 404 * first indicate they need a signal, 405 * then retry the atomic acquire, and then, 406 * on failure, block. 407 * CANCELLED: This node is cancelled due to timeout or interrupt. 408 * Nodes never leave this state. In particular, 409 * a thread with cancelled node never again blocks. 410 * CONDITION: This node is currently on a condition queue. 411 * It will not be used as a sync queue node 412 * until transferred, at which time the status 413 * will be set to 0. (Use of this value here has 414 * nothing to do with the other uses of the 415 * field, but simplifies mechanics.) 416 * PROPAGATE: A releaseShared should be propagated to other 417 * nodes. This is set (for head node only) in 418 * doReleaseShared to ensure propagation 419 * continues, even if other operations have 420 * since intervened. 421 * 0: None of the above 422 * 423 * The values are arranged numerically to simplify use. 424 * Non-negative values mean that a node doesn't need to 425 * signal. So, most code doesn't need to check for particular 426 * values, just for sign. 427 * 428 * The field is initialized to 0 for normal sync nodes, and 429 * CONDITION for condition nodes. It is modified using CAS 430 * (or when possible, unconditional volatile writes). 431 */ 432 volatile int waitStatus; 433 434 /** 435 * Link to predecessor node that current node/thread relies on 436 * for checking waitStatus. Assigned during enqueing, and nulled 437 * out (for sake of GC) only upon dequeuing. Also, upon 438 * cancellation of a predecessor, we short-circuit while 439 * finding a non-cancelled one, which will always exist 440 * because the head node is never cancelled: A node becomes 441 * head only as a result of successful acquire. A 442 * cancelled thread never succeeds in acquiring, and a thread only 443 * cancels itself, not any other node. 444 */ 445 volatile Node prev; 446 447 /** 448 * Link to the successor node that the current node/thread 449 * unparks upon release. Assigned during enqueuing, adjusted 450 * when bypassing cancelled predecessors, and nulled out (for 451 * sake of GC) when dequeued. The enq operation does not 452 * assign next field of a predecessor until after attachment, 453 * so seeing a null next field does not necessarily mean that 454 * node is at end of queue. However, if a next field appears 455 * to be null, we can scan prev's from the tail to 456 * double-check. The next field of cancelled nodes is set to 457 * point to the node itself instead of null, to make life 458 * easier for isOnSyncQueue. 459 */ 460 volatile Node next; 461 462 /** 463 * The thread that enqueued this node. Initialized on 464 * construction and nulled out after use. 465 */ 466 volatile Thread thread; 467 468 /** 469 * Link to next node waiting on condition, or the special 470 * value SHARED. Because condition queues are accessed only 471 * when holding in exclusive mode, we just need a simple 472 * linked queue to hold nodes while they are waiting on 473 * conditions. They are then transferred to the queue to 474 * re-acquire. And because conditions can only be exclusive, 475 * we save a field by using special value to indicate shared 476 * mode. 477 */ 478 Node nextWaiter; 479 480 /** 481 * Returns true if node is waiting in shared mode 482 */ 483 final boolean isShared() { 484 return nextWaiter == SHARED; 485 } 486 487 /** 488 * Returns previous node, or throws NullPointerException if null. 489 * Use when predecessor cannot be null. The null check could 490 * be elided, but is present to help the VM. 491 * 492 * @return the predecessor of this node 493 */ 494 final Node predecessor() throws NullPointerException { 495 Node p = prev; 496 if (p == null) 497 throw new NullPointerException(); 498 else 499 return p; 500 } 501 502 Node() { // Used to establish initial head or SHARED marker 503 } 504 505 Node(Thread thread, Node mode) { // Used by addWaiter 506 this.nextWaiter = mode; 507 this.thread = thread; 508 } 509 510 Node(Thread thread, int waitStatus) { // Used by Condition 511 this.waitStatus = waitStatus; 512 this.thread = thread; 513 } 514 } 515 516 /** 517 * Head of the wait queue, lazily initialized. Except for 518 * initialization, it is modified only via method setHead. Note: 519 * If head exists, its waitStatus is guaranteed not to be 520 * CANCELLED. 521 */ 522 private transient volatile Node head; 523 524 /** 525 * Tail of the wait queue, lazily initialized. Modified only via 526 * method enq to add new wait node. 527 */ 528 private transient volatile Node tail; 529 530 /** 531 * The synchronization state. 532 */ 533 private volatile int state; 534 535 /** 536 * Returns the current value of synchronization state. 537 * This operation has memory semantics of a <tt>volatile</tt> read. 538 * @return current state value 539 */ 540 protected final int getState() { 541 return state; 542 } 543 544 /** 545 * Sets the value of synchronization state. 546 * This operation has memory semantics of a <tt>volatile</tt> write. 547 * @param newState the new state value 548 */ 549 protected final void setState(int newState) { 550 state = newState; 551 } 552 553 /** 554 * Atomically sets synchronization state to the given updated 555 * value if the current state value equals the expected value. 556 * This operation has memory semantics of a <tt>volatile</tt> read 557 * and write. 558 * 559 * @param expect the expected value 560 * @param update the new value 561 * @return true if successful. False return indicates that the actual 562 * value was not equal to the expected value. 563 */ 564 protected final boolean compareAndSetState(int expect, int update) { 565 // See below for intrinsics setup to support this 566 return unsafe.compareAndSwapInt(this, stateOffset, expect, update); 567 } 568 569 // Queuing utilities 570 571 /** 572 * The number of nanoseconds for which it is faster to spin 573 * rather than to use timed park. A rough estimate suffices 574 * to improve responsiveness with very short timeouts. 575 */ 576 static final long spinForTimeoutThreshold = 1000L; 577 578 /** 579 * Inserts node into queue, initializing if necessary. See picture above. 580 * @param node the node to insert 581 * @return node's predecessor 582 */ 583 private Node enq(final Node node) { 584 for (;;) { 585 Node t = tail; 586 if (t == null) { // Must initialize 587 if (compareAndSetHead(new Node())) 588 tail = head; 589 } else { 590 node.prev = t; 591 if (compareAndSetTail(t, node)) { 592 t.next = node; 593 return t; 594 } 595 } 596 } 597 } 598 599 /** 600 * Creates and enqueues node for current thread and given mode. 601 * 602 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 603 * @return the new node 604 */ 605 private Node addWaiter(Node mode) { 606 Node node = new Node(Thread.currentThread(), mode); 607 // Try the fast path of enq; backup to full enq on failure 608 Node pred = tail; 609 if (pred != null) { 610 node.prev = pred; 611 if (compareAndSetTail(pred, node)) { 612 pred.next = node; 613 return node; 614 } 615 } 616 enq(node); 617 return node; 618 } 619 620 /** 621 * Sets head of queue to be node, thus dequeuing. Called only by 622 * acquire methods. Also nulls out unused fields for sake of GC 623 * and to suppress unnecessary signals and traversals. 624 * 625 * @param node the node 626 */ 627 private void setHead(Node node) { 628 head = node; 629 node.thread = null; 630 node.prev = null; 631 } 632 633 /** 634 * Wakes up node's successor, if one exists. 635 * 636 * @param node the node 637 */ 638 private void unparkSuccessor(Node node) { 639 /* 640 * If status is negative (i.e., possibly needing signal) try 641 * to clear in anticipation of signalling. It is OK if this 642 * fails or if status is changed by waiting thread. 643 */ 644 int ws = node.waitStatus; 645 if (ws < 0) 646 compareAndSetWaitStatus(node, ws, 0); 647 648 /* 649 * Thread to unpark is held in successor, which is normally 650 * just the next node. But if cancelled or apparently null, 651 * traverse backwards from tail to find the actual 652 * non-cancelled successor. 653 */ 654 Node s = node.next; 655 if (s == null || s.waitStatus > 0) { 656 s = null; 657 for (Node t = tail; t != null && t != node; t = t.prev) 658 if (t.waitStatus <= 0) 659 s = t; 660 } 661 if (s != null) 662 LockSupport.unpark(s.thread); 663 } 664 665 /** 666 * Release action for shared mode -- signal successor and ensure 667 * propagation. (Note: For exclusive mode, release just amounts 668 * to calling unparkSuccessor of head if it needs signal.) 669 */ 670 private void doReleaseShared() { 671 /* 672 * Ensure that a release propagates, even if there are other 673 * in-progress acquires/releases. This proceeds in the usual 674 * way of trying to unparkSuccessor of head if it needs 675 * signal. But if it does not, status is set to PROPAGATE to 676 * ensure that upon release, propagation continues. 677 * Additionally, we must loop in case a new node is added 678 * while we are doing this. Also, unlike other uses of 679 * unparkSuccessor, we need to know if CAS to reset status 680 * fails, if so rechecking. 681 */ 682 for (;;) { 683 Node h = head; 684 if (h != null && h != tail) { 685 int ws = h.waitStatus; 686 if (ws == Node.SIGNAL) { 687 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) 688 continue; // loop to recheck cases 689 unparkSuccessor(h); 690 } 691 else if (ws == 0 && 692 !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) 693 continue; // loop on failed CAS 694 } 695 if (h == head) // loop if head changed 696 break; 697 } 698 } 699 700 /** 701 * Sets head of queue, and checks if successor may be waiting 702 * in shared mode, if so propagating if either propagate > 0 or 703 * PROPAGATE status was set. 704 * 705 * @param node the node 706 * @param propagate the return value from a tryAcquireShared 707 */ 708 private void setHeadAndPropagate(Node node, int propagate) { 709 Node h = head; // Record old head for check below 710 setHead(node); 711 /* 712 * Try to signal next queued node if: 713 * Propagation was indicated by caller, 714 * or was recorded (as h.waitStatus) by a previous operation 715 * (note: this uses sign-check of waitStatus because 716 * PROPAGATE status may transition to SIGNAL.) 717 * and 718 * The next node is waiting in shared mode, 719 * or we don't know, because it appears null 720 * 721 * The conservatism in both of these checks may cause 722 * unnecessary wake-ups, but only when there are multiple 723 * racing acquires/releases, so most need signals now or soon 724 * anyway. 725 */ 726 if (propagate > 0 || h == null || h.waitStatus < 0) { 727 Node s = node.next; 728 if (s == null || s.isShared()) 729 doReleaseShared(); 730 } 731 } 732 733 // Utilities for various versions of acquire 734 735 /** 736 * Cancels an ongoing attempt to acquire. 737 * 738 * @param node the node 739 */ 740 private void cancelAcquire(Node node) { 741 // Ignore if node doesn't exist 742 if (node == null) 743 return; 744 745 node.thread = null; 746 747 // Skip cancelled predecessors 748 Node pred = node.prev; 749 while (pred.waitStatus > 0) 750 node.prev = pred = pred.prev; 751 752 // predNext is the apparent node to unsplice. CASes below will 753 // fail if not, in which case, we lost race vs another cancel 754 // or signal, so no further action is necessary. 755 Node predNext = pred.next; 756 757 // Can use unconditional write instead of CAS here. 758 // After this atomic step, other Nodes can skip past us. 759 // Before, we are free of interference from other threads. 760 node.waitStatus = Node.CANCELLED; 761 762 // If we are the tail, remove ourselves. 763 if (node == tail && compareAndSetTail(node, pred)) { 764 compareAndSetNext(pred, predNext, null); 765 } else { 766 // If successor needs signal, try to set pred's next-link 767 // so it will get one. Otherwise wake it up to propagate. 768 int ws; 769 if (pred != head && 770 ((ws = pred.waitStatus) == Node.SIGNAL || 771 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && 772 pred.thread != null) { 773 Node next = node.next; 774 if (next != null && next.waitStatus <= 0) 775 compareAndSetNext(pred, predNext, next); 776 } else { 777 unparkSuccessor(node); 778 } 779 780 node.next = node; // help GC 781 } 782 } 783 784 /** 785 * Checks and updates status for a node that failed to acquire. 786 * Returns true if thread should block. This is the main signal 787 * control in all acquire loops. Requires that pred == node.prev 788 * 789 * @param pred node's predecessor holding status 790 * @param node the node 791 * @return {@code true} if thread should block 792 */ 793 private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { 794 int ws = pred.waitStatus; 795 if (ws == Node.SIGNAL) 796 /* 797 * This node has already set status asking a release 798 * to signal it, so it can safely park. 799 */ 800 return true; 801 if (ws > 0) { 802 /* 803 * Predecessor was cancelled. Skip over predecessors and 804 * indicate retry. 805 */ 806 do { 807 node.prev = pred = pred.prev; 808 } while (pred.waitStatus > 0); 809 pred.next = node; 810 } else { 811 /* 812 * waitStatus must be 0 or PROPAGATE. Indicate that we 813 * need a signal, but don't park yet. Caller will need to 814 * retry to make sure it cannot acquire before parking. 815 */ 816 compareAndSetWaitStatus(pred, ws, Node.SIGNAL); 817 } 818 return false; 819 } 820 821 /** 822 * Convenience method to interrupt current thread. 823 */ 824 private static void selfInterrupt() { 825 Thread.currentThread().interrupt(); 826 } 827 828 /** 829 * Convenience method to park and then check if interrupted 830 * 831 * @return {@code true} if interrupted 832 */ 833 private final boolean parkAndCheckInterrupt() { 834 LockSupport.park(this); 835 return Thread.interrupted(); 836 } 837 838 /* 839 * Various flavors of acquire, varying in exclusive/shared and 840 * control modes. Each is mostly the same, but annoyingly 841 * different. Only a little bit of factoring is possible due to 842 * interactions of exception mechanics (including ensuring that we 843 * cancel if tryAcquire throws exception) and other control, at 844 * least not without hurting performance too much. 845 */ 846 847 /** 848 * Acquires in exclusive uninterruptible mode for thread already in 849 * queue. Used by condition wait methods as well as acquire. 850 * 851 * @param node the node 852 * @param arg the acquire argument 853 * @return {@code true} if interrupted while waiting 854 */ 855 final boolean acquireQueued(final Node node, int arg) { 856 boolean failed = true; 857 try { 858 boolean interrupted = false; 859 for (;;) { 860 final Node p = node.predecessor(); 861 if (p == head && tryAcquire(arg)) { 862 setHead(node); 863 p.next = null; // help GC 864 failed = false; 865 return interrupted; 866 } 867 if (shouldParkAfterFailedAcquire(p, node) && 868 parkAndCheckInterrupt()) 869 interrupted = true; 870 } 871 } finally { 872 if (failed) 873 cancelAcquire(node); 874 } 875 } 876 877 /** 878 * Acquires in exclusive interruptible mode. 879 * @param arg the acquire argument 880 */ 881 private void doAcquireInterruptibly(int arg) 882 throws InterruptedException { 883 final Node node = addWaiter(Node.EXCLUSIVE); 884 boolean failed = true; 885 try { 886 for (;;) { 887 final Node p = node.predecessor(); 888 if (p == head && tryAcquire(arg)) { 889 setHead(node); 890 p.next = null; // help GC 891 failed = false; 892 return; 893 } 894 if (shouldParkAfterFailedAcquire(p, node) && 895 parkAndCheckInterrupt()) 896 throw new InterruptedException(); 897 } 898 } finally { 899 if (failed) 900 cancelAcquire(node); 901 } 902 } 903 904 /** 905 * Acquires in exclusive timed mode. 906 * 907 * @param arg the acquire argument 908 * @param nanosTimeout max wait time 909 * @return {@code true} if acquired 910 */ 911 private boolean doAcquireNanos(int arg, long nanosTimeout) 912 throws InterruptedException { 913 long lastTime = System.nanoTime(); 914 final Node node = addWaiter(Node.EXCLUSIVE); 915 boolean failed = true; 916 try { 917 for (;;) { 918 final Node p = node.predecessor(); 919 if (p == head && tryAcquire(arg)) { 920 setHead(node); 921 p.next = null; // help GC 922 failed = false; 923 return true; 924 } 925 if (nanosTimeout <= 0) 926 return false; 927 if (shouldParkAfterFailedAcquire(p, node) && 928 nanosTimeout > spinForTimeoutThreshold) 929 LockSupport.parkNanos(this, nanosTimeout); 930 long now = System.nanoTime(); 931 nanosTimeout -= now - lastTime; 932 lastTime = now; 933 if (Thread.interrupted()) 934 throw new InterruptedException(); 935 } 936 } finally { 937 if (failed) 938 cancelAcquire(node); 939 } 940 } 941 942 /** 943 * Acquires in shared uninterruptible mode. 944 * @param arg the acquire argument 945 */ 946 private void doAcquireShared(int arg) { 947 final Node node = addWaiter(Node.SHARED); 948 boolean failed = true; 949 try { 950 boolean interrupted = false; 951 for (;;) { 952 final Node p = node.predecessor(); 953 if (p == head) { 954 int r = tryAcquireShared(arg); 955 if (r >= 0) { 956 setHeadAndPropagate(node, r); 957 p.next = null; // help GC 958 if (interrupted) 959 selfInterrupt(); 960 failed = false; 961 return; 962 } 963 } 964 if (shouldParkAfterFailedAcquire(p, node) && 965 parkAndCheckInterrupt()) 966 interrupted = true; 967 } 968 } finally { 969 if (failed) 970 cancelAcquire(node); 971 } 972 } 973 974 /** 975 * Acquires in shared interruptible mode. 976 * @param arg the acquire argument 977 */ 978 private void doAcquireSharedInterruptibly(int arg) 979 throws InterruptedException { 980 final Node node = addWaiter(Node.SHARED); 981 boolean failed = true; 982 try { 983 for (;;) { 984 final Node p = node.predecessor(); 985 if (p == head) { 986 int r = tryAcquireShared(arg); 987 if (r >= 0) { 988 setHeadAndPropagate(node, r); 989 p.next = null; // help GC 990 failed = false; 991 return; 992 } 993 } 994 if (shouldParkAfterFailedAcquire(p, node) && 995 parkAndCheckInterrupt()) 996 throw new InterruptedException(); 997 } 998 } finally { 999 if (failed) 1000 cancelAcquire(node); 1001 } 1002 } 1003 1004 /** 1005 * Acquires in shared timed mode. 1006 * 1007 * @param arg the acquire argument 1008 * @param nanosTimeout max wait time 1009 * @return {@code true} if acquired 1010 */ 1011 private boolean doAcquireSharedNanos(int arg, long nanosTimeout) 1012 throws InterruptedException { 1013 1014 long lastTime = System.nanoTime(); 1015 final Node node = addWaiter(Node.SHARED); 1016 boolean failed = true; 1017 try { 1018 for (;;) { 1019 final Node p = node.predecessor(); 1020 if (p == head) { 1021 int r = tryAcquireShared(arg); 1022 if (r >= 0) { 1023 setHeadAndPropagate(node, r); 1024 p.next = null; // help GC 1025 failed = false; 1026 return true; 1027 } 1028 } 1029 if (nanosTimeout <= 0) 1030 return false; 1031 if (shouldParkAfterFailedAcquire(p, node) && 1032 nanosTimeout > spinForTimeoutThreshold) 1033 LockSupport.parkNanos(this, nanosTimeout); 1034 long now = System.nanoTime(); 1035 nanosTimeout -= now - lastTime; 1036 lastTime = now; 1037 if (Thread.interrupted()) 1038 throw new InterruptedException(); 1039 } 1040 } finally { 1041 if (failed) 1042 cancelAcquire(node); 1043 } 1044 } 1045 1046 // Main exported methods 1047 1048 /** 1049 * Attempts to acquire in exclusive mode. This method should query 1050 * if the state of the object permits it to be acquired in the 1051 * exclusive mode, and if so to acquire it. 1052 * 1053 * <p>This method is always invoked by the thread performing 1054 * acquire. If this method reports failure, the acquire method 1055 * may queue the thread, if it is not already queued, until it is 1056 * signalled by a release from some other thread. This can be used 1057 * to implement method {@link Lock#tryLock()}. 1058 * 1059 * <p>The default 1060 * implementation throws {@link UnsupportedOperationException}. 1061 * 1062 * @param arg the acquire argument. This value is always the one 1063 * passed to an acquire method, or is the value saved on entry 1064 * to a condition wait. The value is otherwise uninterpreted 1065 * and can represent anything you like. 1066 * @return {@code true} if successful. Upon success, this object has 1067 * been acquired. 1068 * @throws IllegalMonitorStateException if acquiring would place this 1069 * synchronizer in an illegal state. This exception must be 1070 * thrown in a consistent fashion for synchronization to work 1071 * correctly. 1072 * @throws UnsupportedOperationException if exclusive mode is not supported 1073 */ 1074 protected boolean tryAcquire(int arg) { 1075 throw new UnsupportedOperationException(); 1076 } 1077 1078 /** 1079 * Attempts to set the state to reflect a release in exclusive 1080 * mode. 1081 * 1082 * <p>This method is always invoked by the thread performing release. 1083 * 1084 * <p>The default implementation throws 1085 * {@link UnsupportedOperationException}. 1086 * 1087 * @param arg the release argument. This value is always the one 1088 * passed to a release method, or the current state value upon 1089 * entry to a condition wait. The value is otherwise 1090 * uninterpreted and can represent anything you like. 1091 * @return {@code true} if this object is now in a fully released 1092 * state, so that any waiting threads may attempt to acquire; 1093 * and {@code false} otherwise. 1094 * @throws IllegalMonitorStateException if releasing would place this 1095 * synchronizer in an illegal state. This exception must be 1096 * thrown in a consistent fashion for synchronization to work 1097 * correctly. 1098 * @throws UnsupportedOperationException if exclusive mode is not supported 1099 */ 1100 protected boolean tryRelease(int arg) { 1101 throw new UnsupportedOperationException(); 1102 } 1103 1104 /** 1105 * Attempts to acquire in shared mode. This method should query if 1106 * the state of the object permits it to be acquired in the shared 1107 * mode, and if so to acquire it. 1108 * 1109 * <p>This method is always invoked by the thread performing 1110 * acquire. If this method reports failure, the acquire method 1111 * may queue the thread, if it is not already queued, until it is 1112 * signalled by a release from some other thread. 1113 * 1114 * <p>The default implementation throws {@link 1115 * UnsupportedOperationException}. 1116 * 1117 * @param arg the acquire argument. This value is always the one 1118 * passed to an acquire method, or is the value saved on entry 1119 * to a condition wait. The value is otherwise uninterpreted 1120 * and can represent anything you like. 1121 * @return a negative value on failure; zero if acquisition in shared 1122 * mode succeeded but no subsequent shared-mode acquire can 1123 * succeed; and a positive value if acquisition in shared 1124 * mode succeeded and subsequent shared-mode acquires might 1125 * also succeed, in which case a subsequent waiting thread 1126 * must check availability. (Support for three different 1127 * return values enables this method to be used in contexts 1128 * where acquires only sometimes act exclusively.) Upon 1129 * success, this object has been acquired. 1130 * @throws IllegalMonitorStateException if acquiring would place this 1131 * synchronizer in an illegal state. This exception must be 1132 * thrown in a consistent fashion for synchronization to work 1133 * correctly. 1134 * @throws UnsupportedOperationException if shared mode is not supported 1135 */ 1136 protected int tryAcquireShared(int arg) { 1137 throw new UnsupportedOperationException(); 1138 } 1139 1140 /** 1141 * Attempts to set the state to reflect a release in shared mode. 1142 * 1143 * <p>This method is always invoked by the thread performing release. 1144 * 1145 * <p>The default implementation throws 1146 * {@link UnsupportedOperationException}. 1147 * 1148 * @param arg the release argument. This value is always the one 1149 * passed to a release method, or the current state value upon 1150 * entry to a condition wait. The value is otherwise 1151 * uninterpreted and can represent anything you like. 1152 * @return {@code true} if this release of shared mode may permit a 1153 * waiting acquire (shared or exclusive) to succeed; and 1154 * {@code false} otherwise 1155 * @throws IllegalMonitorStateException if releasing would place this 1156 * synchronizer in an illegal state. This exception must be 1157 * thrown in a consistent fashion for synchronization to work 1158 * correctly. 1159 * @throws UnsupportedOperationException if shared mode is not supported 1160 */ 1161 protected boolean tryReleaseShared(int arg) { 1162 throw new UnsupportedOperationException(); 1163 } 1164 1165 /** 1166 * Returns {@code true} if synchronization is held exclusively with 1167 * respect to the current (calling) thread. This method is invoked 1168 * upon each call to a non-waiting {@link ConditionObject} method. 1169 * (Waiting methods instead invoke {@link #release}.) 1170 * 1171 * <p>The default implementation throws {@link 1172 * UnsupportedOperationException}. This method is invoked 1173 * internally only within {@link ConditionObject} methods, so need 1174 * not be defined if conditions are not used. 1175 * 1176 * @return {@code true} if synchronization is held exclusively; 1177 * {@code false} otherwise 1178 * @throws UnsupportedOperationException if conditions are not supported 1179 */ 1180 protected boolean isHeldExclusively() { 1181 throw new UnsupportedOperationException(); 1182 } 1183 1184 /** 1185 * Acquires in exclusive mode, ignoring interrupts. Implemented 1186 * by invoking at least once {@link #tryAcquire}, 1187 * returning on success. Otherwise the thread is queued, possibly 1188 * repeatedly blocking and unblocking, invoking {@link 1189 * #tryAcquire} until success. This method can be used 1190 * to implement method {@link Lock#lock}. 1191 * 1192 * @param arg the acquire argument. This value is conveyed to 1193 * {@link #tryAcquire} but is otherwise uninterpreted and 1194 * can represent anything you like. 1195 */ 1196 public final void acquire(int arg) { 1197 if (!tryAcquire(arg) && 1198 acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) 1199 selfInterrupt(); 1200 } 1201 1202 /** 1203 * Acquires in exclusive mode, aborting if interrupted. 1204 * Implemented by first checking interrupt status, then invoking 1205 * at least once {@link #tryAcquire}, returning on 1206 * success. Otherwise the thread is queued, possibly repeatedly 1207 * blocking and unblocking, invoking {@link #tryAcquire} 1208 * until success or the thread is interrupted. This method can be 1209 * used to implement method {@link Lock#lockInterruptibly}. 1210 * 1211 * @param arg the acquire argument. This value is conveyed to 1212 * {@link #tryAcquire} but is otherwise uninterpreted and 1213 * can represent anything you like. 1214 * @throws InterruptedException if the current thread is interrupted 1215 */ 1216 public final void acquireInterruptibly(int arg) 1217 throws InterruptedException { 1218 if (Thread.interrupted()) 1219 throw new InterruptedException(); 1220 if (!tryAcquire(arg)) 1221 doAcquireInterruptibly(arg); 1222 } 1223 1224 /** 1225 * Attempts to acquire in exclusive mode, aborting if interrupted, 1226 * and failing if the given timeout elapses. Implemented by first 1227 * checking interrupt status, then invoking at least once {@link 1228 * #tryAcquire}, returning on success. Otherwise, the thread is 1229 * queued, possibly repeatedly blocking and unblocking, invoking 1230 * {@link #tryAcquire} until success or the thread is interrupted 1231 * or the timeout elapses. This method can be used to implement 1232 * method {@link Lock#tryLock(long, TimeUnit)}. 1233 * 1234 * @param arg the acquire argument. This value is conveyed to 1235 * {@link #tryAcquire} but is otherwise uninterpreted and 1236 * can represent anything you like. 1237 * @param nanosTimeout the maximum number of nanoseconds to wait 1238 * @return {@code true} if acquired; {@code false} if timed out 1239 * @throws InterruptedException if the current thread is interrupted 1240 */ 1241 public final boolean tryAcquireNanos(int arg, long nanosTimeout) 1242 throws InterruptedException { 1243 if (Thread.interrupted()) 1244 throw new InterruptedException(); 1245 return tryAcquire(arg) || 1246 doAcquireNanos(arg, nanosTimeout); 1247 } 1248 1249 /** 1250 * Releases in exclusive mode. Implemented by unblocking one or 1251 * more threads if {@link #tryRelease} returns true. 1252 * This method can be used to implement method {@link Lock#unlock}. 1253 * 1254 * @param arg the release argument. This value is conveyed to 1255 * {@link #tryRelease} but is otherwise uninterpreted and 1256 * can represent anything you like. 1257 * @return the value returned from {@link #tryRelease} 1258 */ 1259 public final boolean release(int arg) { 1260 if (tryRelease(arg)) { 1261 Node h = head; 1262 if (h != null && h.waitStatus != 0) 1263 unparkSuccessor(h); 1264 return true; 1265 } 1266 return false; 1267 } 1268 1269 /** 1270 * Acquires in shared mode, ignoring interrupts. Implemented by 1271 * first invoking at least once {@link #tryAcquireShared}, 1272 * returning on success. Otherwise the thread is queued, possibly 1273 * repeatedly blocking and unblocking, invoking {@link 1274 * #tryAcquireShared} until success. 1275 * 1276 * @param arg the acquire argument. This value is conveyed to 1277 * {@link #tryAcquireShared} but is otherwise uninterpreted 1278 * and can represent anything you like. 1279 */ 1280 public final void acquireShared(int arg) { 1281 if (tryAcquireShared(arg) < 0) 1282 doAcquireShared(arg); 1283 } 1284 1285 /** 1286 * Acquires in shared mode, aborting if interrupted. Implemented 1287 * by first checking interrupt status, then invoking at least once 1288 * {@link #tryAcquireShared}, returning on success. Otherwise the 1289 * thread is queued, possibly repeatedly blocking and unblocking, 1290 * invoking {@link #tryAcquireShared} until success or the thread 1291 * is interrupted. 1292 * @param arg the acquire argument 1293 * This value is conveyed to {@link #tryAcquireShared} but is 1294 * otherwise uninterpreted and can represent anything 1295 * you like. 1296 * @throws InterruptedException if the current thread is interrupted 1297 */ 1298 public final void acquireSharedInterruptibly(int arg) 1299 throws InterruptedException { 1300 if (Thread.interrupted()) 1301 throw new InterruptedException(); 1302 if (tryAcquireShared(arg) < 0) 1303 doAcquireSharedInterruptibly(arg); 1304 } 1305 1306 /** 1307 * Attempts to acquire in shared mode, aborting if interrupted, and 1308 * failing if the given timeout elapses. Implemented by first 1309 * checking interrupt status, then invoking at least once {@link 1310 * #tryAcquireShared}, returning on success. Otherwise, the 1311 * thread is queued, possibly repeatedly blocking and unblocking, 1312 * invoking {@link #tryAcquireShared} until success or the thread 1313 * is interrupted or the timeout elapses. 1314 * 1315 * @param arg the acquire argument. This value is conveyed to 1316 * {@link #tryAcquireShared} but is otherwise uninterpreted 1317 * and can represent anything you like. 1318 * @param nanosTimeout the maximum number of nanoseconds to wait 1319 * @return {@code true} if acquired; {@code false} if timed out 1320 * @throws InterruptedException if the current thread is interrupted 1321 */ 1322 public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) 1323 throws InterruptedException { 1324 if (Thread.interrupted()) 1325 throw new InterruptedException(); 1326 return tryAcquireShared(arg) >= 0 || 1327 doAcquireSharedNanos(arg, nanosTimeout); 1328 } 1329 1330 /** 1331 * Releases in shared mode. Implemented by unblocking one or more 1332 * threads if {@link #tryReleaseShared} returns true. 1333 * 1334 * @param arg the release argument. This value is conveyed to 1335 * {@link #tryReleaseShared} but is otherwise uninterpreted 1336 * and can represent anything you like. 1337 * @return the value returned from {@link #tryReleaseShared} 1338 */ 1339 public final boolean releaseShared(int arg) { 1340 if (tryReleaseShared(arg)) { 1341 doReleaseShared(); 1342 return true; 1343 } 1344 return false; 1345 } 1346 1347 // Queue inspection methods 1348 1349 /** 1350 * Queries whether any threads are waiting to acquire. Note that 1351 * because cancellations due to interrupts and timeouts may occur 1352 * at any time, a {@code true} return does not guarantee that any 1353 * other thread will ever acquire. 1354 * 1355 * <p>In this implementation, this operation returns in 1356 * constant time. 1357 * 1358 * @return {@code true} if there may be other threads waiting to acquire 1359 */ 1360 public final boolean hasQueuedThreads() { 1361 return head != tail; 1362 } 1363 1364 /** 1365 * Queries whether any threads have ever contended to acquire this 1366 * synchronizer; that is if an acquire method has ever blocked. 1367 * 1368 * <p>In this implementation, this operation returns in 1369 * constant time. 1370 * 1371 * @return {@code true} if there has ever been contention 1372 */ 1373 public final boolean hasContended() { 1374 return head != null; 1375 } 1376 1377 /** 1378 * Returns the first (longest-waiting) thread in the queue, or 1379 * {@code null} if no threads are currently queued. 1380 * 1381 * <p>In this implementation, this operation normally returns in 1382 * constant time, but may iterate upon contention if other threads are 1383 * concurrently modifying the queue. 1384 * 1385 * @return the first (longest-waiting) thread in the queue, or 1386 * {@code null} if no threads are currently queued 1387 */ 1388 public final Thread getFirstQueuedThread() { 1389 // handle only fast path, else relay 1390 return (head == tail) ? null : fullGetFirstQueuedThread(); 1391 } 1392 1393 /** 1394 * Version of getFirstQueuedThread called when fastpath fails 1395 */ 1396 private Thread fullGetFirstQueuedThread() { 1397 /* 1398 * The first node is normally head.next. Try to get its 1399 * thread field, ensuring consistent reads: If thread 1400 * field is nulled out or s.prev is no longer head, then 1401 * some other thread(s) concurrently performed setHead in 1402 * between some of our reads. We try this twice before 1403 * resorting to traversal. 1404 */ 1405 Node h, s; 1406 Thread st; 1407 if (((h = head) != null && (s = h.next) != null && 1408 s.prev == head && (st = s.thread) != null) || 1409 ((h = head) != null && (s = h.next) != null && 1410 s.prev == head && (st = s.thread) != null)) 1411 return st; 1412 1413 /* 1414 * Head's next field might not have been set yet, or may have 1415 * been unset after setHead. So we must check to see if tail 1416 * is actually first node. If not, we continue on, safely 1417 * traversing from tail back to head to find first, 1418 * guaranteeing termination. 1419 */ 1420 1421 Node t = tail; 1422 Thread firstThread = null; 1423 while (t != null && t != head) { 1424 Thread tt = t.thread; 1425 if (tt != null) 1426 firstThread = tt; 1427 t = t.prev; 1428 } 1429 return firstThread; 1430 } 1431 1432 /** 1433 * Returns true if the given thread is currently queued. 1434 * 1435 * <p>This implementation traverses the queue to determine 1436 * presence of the given thread. 1437 * 1438 * @param thread the thread 1439 * @return {@code true} if the given thread is on the queue 1440 * @throws NullPointerException if the thread is null 1441 */ 1442 public final boolean isQueued(Thread thread) { 1443 if (thread == null) 1444 throw new NullPointerException(); 1445 for (Node p = tail; p != null; p = p.prev) 1446 if (p.thread == thread) 1447 return true; 1448 return false; 1449 } 1450 1451 /** 1452 * Returns {@code true} if the apparent first queued thread, if one 1453 * exists, is waiting in exclusive mode. If this method returns 1454 * {@code true}, and the current thread is attempting to acquire in 1455 * shared mode (that is, this method is invoked from {@link 1456 * #tryAcquireShared}) then it is guaranteed that the current thread 1457 * is not the first queued thread. Used only as a heuristic in 1458 * ReentrantReadWriteLock. 1459 */ 1460 final boolean apparentlyFirstQueuedIsExclusive() { 1461 Node h, s; 1462 return (h = head) != null && 1463 (s = h.next) != null && 1464 !s.isShared() && 1465 s.thread != null; 1466 } 1467 1468 /** 1469 * Queries whether any threads have been waiting to acquire longer 1470 * than the current thread. 1471 * 1472 * <p>An invocation of this method is equivalent to (but may be 1473 * more efficient than): 1474 * <pre> {@code 1475 * getFirstQueuedThread() != Thread.currentThread() && 1476 * hasQueuedThreads()}</pre> 1477 * 1478 * <p>Note that because cancellations due to interrupts and 1479 * timeouts may occur at any time, a {@code true} return does not 1480 * guarantee that some other thread will acquire before the current 1481 * thread. Likewise, it is possible for another thread to win a 1482 * race to enqueue after this method has returned {@code false}, 1483 * due to the queue being empty. 1484 * 1485 * <p>This method is designed to be used by a fair synchronizer to 1486 * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. 1487 * Such a synchronizer's {@link #tryAcquire} method should return 1488 * {@code false}, and its {@link #tryAcquireShared} method should 1489 * return a negative value, if this method returns {@code true} 1490 * (unless this is a reentrant acquire). For example, the {@code 1491 * tryAcquire} method for a fair, reentrant, exclusive mode 1492 * synchronizer might look like this: 1493 * 1494 * <pre> {@code 1495 * protected boolean tryAcquire(int arg) { 1496 * if (isHeldExclusively()) { 1497 * // A reentrant acquire; increment hold count 1498 * return true; 1499 * } else if (hasQueuedPredecessors()) { 1500 * return false; 1501 * } else { 1502 * // try to acquire normally 1503 * } 1504 * }}</pre> 1505 * 1506 * @return {@code true} if there is a queued thread preceding the 1507 * current thread, and {@code false} if the current thread 1508 * is at the head of the queue or the queue is empty 1509 * @since 1.7 1510 */ 1511 public final boolean hasQueuedPredecessors() { 1512 // The correctness of this depends on head being initialized 1513 // before tail and on head.next being accurate if the current 1514 // thread is first in queue. 1515 Node t = tail; // Read fields in reverse initialization order 1516 Node h = head; 1517 Node s; 1518 return h != t && 1519 ((s = h.next) == null || s.thread != Thread.currentThread()); 1520 } 1521 1522 1523 // Instrumentation and monitoring methods 1524 1525 /** 1526 * Returns an estimate of the number of threads waiting to 1527 * acquire. The value is only an estimate because the number of 1528 * threads may change dynamically while this method traverses 1529 * internal data structures. This method is designed for use in 1530 * monitoring system state, not for synchronization 1531 * control. 1532 * 1533 * @return the estimated number of threads waiting to acquire 1534 */ 1535 public final int getQueueLength() { 1536 int n = 0; 1537 for (Node p = tail; p != null; p = p.prev) { 1538 if (p.thread != null) 1539 ++n; 1540 } 1541 return n; 1542 } 1543 1544 /** 1545 * Returns a collection containing threads that may be waiting to 1546 * acquire. Because the actual set of threads may change 1547 * dynamically while constructing this result, the returned 1548 * collection is only a best-effort estimate. The elements of the 1549 * returned collection are in no particular order. This method is 1550 * designed to facilitate construction of subclasses that provide 1551 * more extensive monitoring facilities. 1552 * 1553 * @return the collection of threads 1554 */ 1555 public final Collection<Thread> getQueuedThreads() { 1556 ArrayList<Thread> list = new ArrayList<Thread>(); 1557 for (Node p = tail; p != null; p = p.prev) { 1558 Thread t = p.thread; 1559 if (t != null) 1560 list.add(t); 1561 } 1562 return list; 1563 } 1564 1565 /** 1566 * Returns a collection containing threads that may be waiting to 1567 * acquire in exclusive mode. This has the same properties 1568 * as {@link #getQueuedThreads} except that it only returns 1569 * those threads waiting due to an exclusive acquire. 1570 * 1571 * @return the collection of threads 1572 */ 1573 public final Collection<Thread> getExclusiveQueuedThreads() { 1574 ArrayList<Thread> list = new ArrayList<Thread>(); 1575 for (Node p = tail; p != null; p = p.prev) { 1576 if (!p.isShared()) { 1577 Thread t = p.thread; 1578 if (t != null) 1579 list.add(t); 1580 } 1581 } 1582 return list; 1583 } 1584 1585 /** 1586 * Returns a collection containing threads that may be waiting to 1587 * acquire in shared mode. This has the same properties 1588 * as {@link #getQueuedThreads} except that it only returns 1589 * those threads waiting due to a shared acquire. 1590 * 1591 * @return the collection of threads 1592 */ 1593 public final Collection<Thread> getSharedQueuedThreads() { 1594 ArrayList<Thread> list = new ArrayList<Thread>(); 1595 for (Node p = tail; p != null; p = p.prev) { 1596 if (p.isShared()) { 1597 Thread t = p.thread; 1598 if (t != null) 1599 list.add(t); 1600 } 1601 } 1602 return list; 1603 } 1604 1605 /** 1606 * Returns a string identifying this synchronizer, as well as its state. 1607 * The state, in brackets, includes the String {@code "State ="} 1608 * followed by the current value of {@link #getState}, and either 1609 * {@code "nonempty"} or {@code "empty"} depending on whether the 1610 * queue is empty. 1611 * 1612 * @return a string identifying this synchronizer, as well as its state 1613 */ 1614 public String toString() { 1615 int s = getState(); 1616 String q = hasQueuedThreads() ? "non" : ""; 1617 return super.toString() + 1618 "[State = " + s + ", " + q + "empty queue]"; 1619 } 1620 1621 1622 // Internal support methods for Conditions 1623 1624 /** 1625 * Returns true if a node, always one that was initially placed on 1626 * a condition queue, is now waiting to reacquire on sync queue. 1627 * @param node the node 1628 * @return true if is reacquiring 1629 */ 1630 final boolean isOnSyncQueue(Node node) { 1631 if (node.waitStatus == Node.CONDITION || node.prev == null) 1632 return false; 1633 if (node.next != null) // If has successor, it must be on queue 1634 return true; 1635 /* 1636 * node.prev can be non-null, but not yet on queue because 1637 * the CAS to place it on queue can fail. So we have to 1638 * traverse from tail to make sure it actually made it. It 1639 * will always be near the tail in calls to this method, and 1640 * unless the CAS failed (which is unlikely), it will be 1641 * there, so we hardly ever traverse much. 1642 */ 1643 return findNodeFromTail(node); 1644 } 1645 1646 /** 1647 * Returns true if node is on sync queue by searching backwards from tail. 1648 * Called only when needed by isOnSyncQueue. 1649 * @return true if present 1650 */ 1651 private boolean findNodeFromTail(Node node) { 1652 Node t = tail; 1653 for (;;) { 1654 if (t == node) 1655 return true; 1656 if (t == null) 1657 return false; 1658 t = t.prev; 1659 } 1660 } 1661 1662 /** 1663 * Transfers a node from a condition queue onto sync queue. 1664 * Returns true if successful. 1665 * @param node the node 1666 * @return true if successfully transferred (else the node was 1667 * cancelled before signal). 1668 */ 1669 final boolean transferForSignal(Node node) { 1670 /* 1671 * If cannot change waitStatus, the node has been cancelled. 1672 */ 1673 if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) 1674 return false; 1675 1676 /* 1677 * Splice onto queue and try to set waitStatus of predecessor to 1678 * indicate that thread is (probably) waiting. If cancelled or 1679 * attempt to set waitStatus fails, wake up to resync (in which 1680 * case the waitStatus can be transiently and harmlessly wrong). 1681 */ 1682 Node p = enq(node); 1683 int ws = p.waitStatus; 1684 if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) 1685 LockSupport.unpark(node.thread); 1686 return true; 1687 } 1688 1689 /** 1690 * Transfers node, if necessary, to sync queue after a cancelled 1691 * wait. Returns true if thread was cancelled before being 1692 * signalled. 1693 * @param current the waiting thread 1694 * @param node its node 1695 * @return true if cancelled before the node was signalled 1696 */ 1697 final boolean transferAfterCancelledWait(Node node) { 1698 if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { 1699 enq(node); 1700 return true; 1701 } 1702 /* 1703 * If we lost out to a signal(), then we can't proceed 1704 * until it finishes its enq(). Cancelling during an 1705 * incomplete transfer is both rare and transient, so just 1706 * spin. 1707 */ 1708 while (!isOnSyncQueue(node)) 1709 Thread.yield(); 1710 return false; 1711 } 1712 1713 /** 1714 * Invokes release with current state value; returns saved state. 1715 * Cancels node and throws exception on failure. 1716 * @param node the condition node for this wait 1717 * @return previous sync state 1718 */ 1719 final int fullyRelease(Node node) { 1720 boolean failed = true; 1721 try { 1722 int savedState = getState(); 1723 if (release(savedState)) { 1724 failed = false; 1725 return savedState; 1726 } else { 1727 throw new IllegalMonitorStateException(); 1728 } 1729 } finally { 1730 if (failed) 1731 node.waitStatus = Node.CANCELLED; 1732 } 1733 } 1734 1735 // Instrumentation methods for conditions 1736 1737 /** 1738 * Queries whether the given ConditionObject 1739 * uses this synchronizer as its lock. 1740 * 1741 * @param condition the condition 1742 * @return <tt>true</tt> if owned 1743 * @throws NullPointerException if the condition is null 1744 */ 1745 public final boolean owns(ConditionObject condition) { 1746 if (condition == null) 1747 throw new NullPointerException(); 1748 return condition.isOwnedBy(this); 1749 } 1750 1751 /** 1752 * Queries whether any threads are waiting on the given condition 1753 * associated with this synchronizer. Note that because timeouts 1754 * and interrupts may occur at any time, a <tt>true</tt> return 1755 * does not guarantee that a future <tt>signal</tt> will awaken 1756 * any threads. This method is designed primarily for use in 1757 * monitoring of the system state. 1758 * 1759 * @param condition the condition 1760 * @return <tt>true</tt> if there are any waiting threads 1761 * @throws IllegalMonitorStateException if exclusive synchronization 1762 * is not held 1763 * @throws IllegalArgumentException if the given condition is 1764 * not associated with this synchronizer 1765 * @throws NullPointerException if the condition is null 1766 */ 1767 public final boolean hasWaiters(ConditionObject condition) { 1768 if (!owns(condition)) 1769 throw new IllegalArgumentException("Not owner"); 1770 return condition.hasWaiters(); 1771 } 1772 1773 /** 1774 * Returns an estimate of the number of threads waiting on the 1775 * given condition associated with this synchronizer. Note that 1776 * because timeouts and interrupts may occur at any time, the 1777 * estimate serves only as an upper bound on the actual number of 1778 * waiters. This method is designed for use in monitoring of the 1779 * system state, not for synchronization control. 1780 * 1781 * @param condition the condition 1782 * @return the estimated number of waiting threads 1783 * @throws IllegalMonitorStateException if exclusive synchronization 1784 * is not held 1785 * @throws IllegalArgumentException if the given condition is 1786 * not associated with this synchronizer 1787 * @throws NullPointerException if the condition is null 1788 */ 1789 public final int getWaitQueueLength(ConditionObject condition) { 1790 if (!owns(condition)) 1791 throw new IllegalArgumentException("Not owner"); 1792 return condition.getWaitQueueLength(); 1793 } 1794 1795 /** 1796 * Returns a collection containing those threads that may be 1797 * waiting on the given condition associated with this 1798 * synchronizer. Because the actual set of threads may change 1799 * dynamically while constructing this result, the returned 1800 * collection is only a best-effort estimate. The elements of the 1801 * returned collection are in no particular order. 1802 * 1803 * @param condition the condition 1804 * @return the collection of threads 1805 * @throws IllegalMonitorStateException if exclusive synchronization 1806 * is not held 1807 * @throws IllegalArgumentException if the given condition is 1808 * not associated with this synchronizer 1809 * @throws NullPointerException if the condition is null 1810 */ 1811 public final Collection<Thread> getWaitingThreads(ConditionObject condition) { 1812 if (!owns(condition)) 1813 throw new IllegalArgumentException("Not owner"); 1814 return condition.getWaitingThreads(); 1815 } 1816 1817 /** 1818 * Condition implementation for a {@link 1819 * AbstractQueuedSynchronizer} serving as the basis of a {@link 1820 * Lock} implementation. 1821 * 1822 * <p>Method documentation for this class describes mechanics, 1823 * not behavioral specifications from the point of view of Lock 1824 * and Condition users. Exported versions of this class will in 1825 * general need to be accompanied by documentation describing 1826 * condition semantics that rely on those of the associated 1827 * <tt>AbstractQueuedSynchronizer</tt>. 1828 * 1829 * <p>This class is Serializable, but all fields are transient, 1830 * so deserialized conditions have no waiters. 1831 */ 1832 public class ConditionObject implements Condition, java.io.Serializable { 1833 private static final long serialVersionUID = 1173984872572414699L; 1834 /** First node of condition queue. */ 1835 private transient Node firstWaiter; 1836 /** Last node of condition queue. */ 1837 private transient Node lastWaiter; 1838 1839 /** 1840 * Creates a new <tt>ConditionObject</tt> instance. 1841 */ 1842 public ConditionObject() { } 1843 1844 // Internal methods 1845 1846 /** 1847 * Adds a new waiter to wait queue. 1848 * @return its new wait node 1849 */ 1850 private Node addConditionWaiter() { 1851 Node t = lastWaiter; 1852 // If lastWaiter is cancelled, clean out. 1853 if (t != null && t.waitStatus != Node.CONDITION) { 1854 unlinkCancelledWaiters(); 1855 t = lastWaiter; 1856 } 1857 Node node = new Node(Thread.currentThread(), Node.CONDITION); 1858 if (t == null) 1859 firstWaiter = node; 1860 else 1861 t.nextWaiter = node; 1862 lastWaiter = node; 1863 return node; 1864 } 1865 1866 /** 1867 * Removes and transfers nodes until hit non-cancelled one or 1868 * null. Split out from signal in part to encourage compilers 1869 * to inline the case of no waiters. 1870 * @param first (non-null) the first node on condition queue 1871 */ 1872 private void doSignal(Node first) { 1873 do { 1874 if ( (firstWaiter = first.nextWaiter) == null) 1875 lastWaiter = null; 1876 first.nextWaiter = null; 1877 } while (!transferForSignal(first) && 1878 (first = firstWaiter) != null); 1879 } 1880 1881 /** 1882 * Removes and transfers all nodes. 1883 * @param first (non-null) the first node on condition queue 1884 */ 1885 private void doSignalAll(Node first) { 1886 lastWaiter = firstWaiter = null; 1887 do { 1888 Node next = first.nextWaiter; 1889 first.nextWaiter = null; 1890 transferForSignal(first); 1891 first = next; 1892 } while (first != null); 1893 } 1894 1895 /** 1896 * Unlinks cancelled waiter nodes from condition queue. 1897 * Called only while holding lock. This is called when 1898 * cancellation occurred during condition wait, and upon 1899 * insertion of a new waiter when lastWaiter is seen to have 1900 * been cancelled. This method is needed to avoid garbage 1901 * retention in the absence of signals. So even though it may 1902 * require a full traversal, it comes into play only when 1903 * timeouts or cancellations occur in the absence of 1904 * signals. It traverses all nodes rather than stopping at a 1905 * particular target to unlink all pointers to garbage nodes 1906 * without requiring many re-traversals during cancellation 1907 * storms. 1908 */ 1909 private void unlinkCancelledWaiters() { 1910 Node t = firstWaiter; 1911 Node trail = null; 1912 while (t != null) { 1913 Node next = t.nextWaiter; 1914 if (t.waitStatus != Node.CONDITION) { 1915 t.nextWaiter = null; 1916 if (trail == null) 1917 firstWaiter = next; 1918 else 1919 trail.nextWaiter = next; 1920 if (next == null) 1921 lastWaiter = trail; 1922 } 1923 else 1924 trail = t; 1925 t = next; 1926 } 1927 } 1928 1929 // public methods 1930 1931 /** 1932 * Moves the longest-waiting thread, if one exists, from the 1933 * wait queue for this condition to the wait queue for the 1934 * owning lock. 1935 * 1936 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 1937 * returns {@code false} 1938 */ 1939 public final void signal() { 1940 if (!isHeldExclusively()) 1941 throw new IllegalMonitorStateException(); 1942 Node first = firstWaiter; 1943 if (first != null) 1944 doSignal(first); 1945 } 1946 1947 /** 1948 * Moves all threads from the wait queue for this condition to 1949 * the wait queue for the owning lock. 1950 * 1951 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 1952 * returns {@code false} 1953 */ 1954 public final void signalAll() { 1955 if (!isHeldExclusively()) 1956 throw new IllegalMonitorStateException(); 1957 Node first = firstWaiter; 1958 if (first != null) 1959 doSignalAll(first); 1960 } 1961 1962 /** 1963 * Implements uninterruptible condition wait. 1964 * <ol> 1965 * <li> Save lock state returned by {@link #getState}. 1966 * <li> Invoke {@link #release} with 1967 * saved state as argument, throwing 1968 * IllegalMonitorStateException if it fails. 1969 * <li> Block until signalled. 1970 * <li> Reacquire by invoking specialized version of 1971 * {@link #acquire} with saved state as argument. 1972 * </ol> 1973 */ 1974 public final void awaitUninterruptibly() { 1975 Node node = addConditionWaiter(); 1976 int savedState = fullyRelease(node); 1977 boolean interrupted = false; 1978 while (!isOnSyncQueue(node)) { 1979 LockSupport.park(this); 1980 if (Thread.interrupted()) 1981 interrupted = true; 1982 } 1983 if (acquireQueued(node, savedState) || interrupted) 1984 selfInterrupt(); 1985 } 1986 1987 /* 1988 * For interruptible waits, we need to track whether to throw 1989 * InterruptedException, if interrupted while blocked on 1990 * condition, versus reinterrupt current thread, if 1991 * interrupted while blocked waiting to re-acquire. 1992 */ 1993 1994 /** Mode meaning to reinterrupt on exit from wait */ 1995 private static final int REINTERRUPT = 1; 1996 /** Mode meaning to throw InterruptedException on exit from wait */ 1997 private static final int THROW_IE = -1; 1998 1999 /** 2000 * Checks for interrupt, returning THROW_IE if interrupted 2001 * before signalled, REINTERRUPT if after signalled, or 2002 * 0 if not interrupted. 2003 */ 2004 private int checkInterruptWhileWaiting(Node node) { 2005 return Thread.interrupted() ? 2006 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 2007 0; 2008 } 2009 2010 /** 2011 * Throws InterruptedException, reinterrupts current thread, or 2012 * does nothing, depending on mode. 2013 */ 2014 private void reportInterruptAfterWait(int interruptMode) 2015 throws InterruptedException { 2016 if (interruptMode == THROW_IE) 2017 throw new InterruptedException(); 2018 else if (interruptMode == REINTERRUPT) 2019 selfInterrupt(); 2020 } 2021 2022 /** 2023 * Implements interruptible condition wait. 2024 * <ol> 2025 * <li> If current thread is interrupted, throw InterruptedException. 2026 * <li> Save lock state returned by {@link #getState}. 2027 * <li> Invoke {@link #release} with 2028 * saved state as argument, throwing 2029 * IllegalMonitorStateException if it fails. 2030 * <li> Block until signalled or interrupted. 2031 * <li> Reacquire by invoking specialized version of 2032 * {@link #acquire} with saved state as argument. 2033 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2034 * </ol> 2035 */ 2036 public final void await() throws InterruptedException { 2037 if (Thread.interrupted()) 2038 throw new InterruptedException(); 2039 Node node = addConditionWaiter(); 2040 int savedState = fullyRelease(node); 2041 int interruptMode = 0; 2042 while (!isOnSyncQueue(node)) { 2043 LockSupport.park(this); 2044 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2045 break; 2046 } 2047 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2048 interruptMode = REINTERRUPT; 2049 if (node.nextWaiter != null) // clean up if cancelled 2050 unlinkCancelledWaiters(); 2051 if (interruptMode != 0) 2052 reportInterruptAfterWait(interruptMode); 2053 } 2054 2055 /** 2056 * Implements timed condition wait. 2057 * <ol> 2058 * <li> If current thread is interrupted, throw InterruptedException. 2059 * <li> Save lock state returned by {@link #getState}. 2060 * <li> Invoke {@link #release} with 2061 * saved state as argument, throwing 2062 * IllegalMonitorStateException if it fails. 2063 * <li> Block until signalled, interrupted, or timed out. 2064 * <li> Reacquire by invoking specialized version of 2065 * {@link #acquire} with saved state as argument. 2066 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2067 * </ol> 2068 */ 2069 public final long awaitNanos(long nanosTimeout) 2070 throws InterruptedException { 2071 if (Thread.interrupted()) 2072 throw new InterruptedException(); 2073 Node node = addConditionWaiter(); 2074 int savedState = fullyRelease(node); 2075 long lastTime = System.nanoTime(); 2076 int interruptMode = 0; 2077 while (!isOnSyncQueue(node)) { 2078 if (nanosTimeout <= 0L) { 2079 transferAfterCancelledWait(node); 2080 break; 2081 } 2082 LockSupport.parkNanos(this, nanosTimeout); 2083 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2084 break; 2085 2086 long now = System.nanoTime(); 2087 nanosTimeout -= now - lastTime; 2088 lastTime = now; 2089 } 2090 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2091 interruptMode = REINTERRUPT; 2092 if (node.nextWaiter != null) 2093 unlinkCancelledWaiters(); 2094 if (interruptMode != 0) 2095 reportInterruptAfterWait(interruptMode); 2096 return nanosTimeout - (System.nanoTime() - lastTime); 2097 } 2098 2099 /** 2100 * Implements absolute timed condition wait. 2101 * <ol> 2102 * <li> If current thread is interrupted, throw InterruptedException. 2103 * <li> Save lock state returned by {@link #getState}. 2104 * <li> Invoke {@link #release} with 2105 * saved state as argument, throwing 2106 * IllegalMonitorStateException if it fails. 2107 * <li> Block until signalled, interrupted, or timed out. 2108 * <li> Reacquire by invoking specialized version of 2109 * {@link #acquire} with saved state as argument. 2110 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2111 * <li> If timed out while blocked in step 4, return false, else true. 2112 * </ol> 2113 */ 2114 public final boolean awaitUntil(Date deadline) 2115 throws InterruptedException { 2116 if (deadline == null) 2117 throw new NullPointerException(); 2118 long abstime = deadline.getTime(); 2119 if (Thread.interrupted()) 2120 throw new InterruptedException(); 2121 Node node = addConditionWaiter(); 2122 int savedState = fullyRelease(node); 2123 boolean timedout = false; 2124 int interruptMode = 0; 2125 while (!isOnSyncQueue(node)) { 2126 if (System.currentTimeMillis() > abstime) { 2127 timedout = transferAfterCancelledWait(node); 2128 break; 2129 } 2130 LockSupport.parkUntil(this, abstime); 2131 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2132 break; 2133 } 2134 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2135 interruptMode = REINTERRUPT; 2136 if (node.nextWaiter != null) 2137 unlinkCancelledWaiters(); 2138 if (interruptMode != 0) 2139 reportInterruptAfterWait(interruptMode); 2140 return !timedout; 2141 } 2142 2143 /** 2144 * Implements timed condition wait. 2145 * <ol> 2146 * <li> If current thread is interrupted, throw InterruptedException. 2147 * <li> Save lock state returned by {@link #getState}. 2148 * <li> Invoke {@link #release} with 2149 * saved state as argument, throwing 2150 * IllegalMonitorStateException if it fails. 2151 * <li> Block until signalled, interrupted, or timed out. 2152 * <li> Reacquire by invoking specialized version of 2153 * {@link #acquire} with saved state as argument. 2154 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2155 * <li> If timed out while blocked in step 4, return false, else true. 2156 * </ol> 2157 */ 2158 public final boolean await(long time, TimeUnit unit) 2159 throws InterruptedException { 2160 if (unit == null) 2161 throw new NullPointerException(); 2162 long nanosTimeout = unit.toNanos(time); 2163 if (Thread.interrupted()) 2164 throw new InterruptedException(); 2165 Node node = addConditionWaiter(); 2166 int savedState = fullyRelease(node); 2167 long lastTime = System.nanoTime(); 2168 boolean timedout = false; 2169 int interruptMode = 0; 2170 while (!isOnSyncQueue(node)) { 2171 if (nanosTimeout <= 0L) { 2172 timedout = transferAfterCancelledWait(node); 2173 break; 2174 } 2175 if (nanosTimeout >= spinForTimeoutThreshold) 2176 LockSupport.parkNanos(this, nanosTimeout); 2177 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2178 break; 2179 long now = System.nanoTime(); 2180 nanosTimeout -= now - lastTime; 2181 lastTime = now; 2182 } 2183 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2184 interruptMode = REINTERRUPT; 2185 if (node.nextWaiter != null) 2186 unlinkCancelledWaiters(); 2187 if (interruptMode != 0) 2188 reportInterruptAfterWait(interruptMode); 2189 return !timedout; 2190 } 2191 2192 // support for instrumentation 2193 2194 /** 2195 * Returns true if this condition was created by the given 2196 * synchronization object. 2197 * 2198 * @return {@code true} if owned 2199 */ 2200 final boolean isOwnedBy(AbstractQueuedSynchronizer sync) { 2201 return sync == AbstractQueuedSynchronizer.this; 2202 } 2203 2204 /** 2205 * Queries whether any threads are waiting on this condition. 2206 * Implements {@link AbstractQueuedSynchronizer#hasWaiters}. 2207 * 2208 * @return {@code true} if there are any waiting threads 2209 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2210 * returns {@code false} 2211 */ 2212 protected final boolean hasWaiters() { 2213 if (!isHeldExclusively()) 2214 throw new IllegalMonitorStateException(); 2215 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2216 if (w.waitStatus == Node.CONDITION) 2217 return true; 2218 } 2219 return false; 2220 } 2221 2222 /** 2223 * Returns an estimate of the number of threads waiting on 2224 * this condition. 2225 * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}. 2226 * 2227 * @return the estimated number of waiting threads 2228 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2229 * returns {@code false} 2230 */ 2231 protected final int getWaitQueueLength() { 2232 if (!isHeldExclusively()) 2233 throw new IllegalMonitorStateException(); 2234 int n = 0; 2235 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2236 if (w.waitStatus == Node.CONDITION) 2237 ++n; 2238 } 2239 return n; 2240 } 2241 2242 /** 2243 * Returns a collection containing those threads that may be 2244 * waiting on this Condition. 2245 * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}. 2246 * 2247 * @return the collection of threads 2248 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2249 * returns {@code false} 2250 */ 2251 protected final Collection<Thread> getWaitingThreads() { 2252 if (!isHeldExclusively()) 2253 throw new IllegalMonitorStateException(); 2254 ArrayList<Thread> list = new ArrayList<Thread>(); 2255 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2256 if (w.waitStatus == Node.CONDITION) { 2257 Thread t = w.thread; 2258 if (t != null) 2259 list.add(t); 2260 } 2261 } 2262 return list; 2263 } 2264 } 2265 2266 /** 2267 * Setup to support compareAndSet. We need to natively implement 2268 * this here: For the sake of permitting future enhancements, we 2269 * cannot explicitly subclass AtomicInteger, which would be 2270 * efficient and useful otherwise. So, as the lesser of evils, we 2271 * natively implement using hotspot intrinsics API. And while we 2272 * are at it, we do the same for other CASable fields (which could 2273 * otherwise be done with atomic field updaters). 2274 */ 2275 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2276 private static final long stateOffset; 2277 private static final long headOffset; 2278 private static final long tailOffset; 2279 private static final long waitStatusOffset; 2280 private static final long nextOffset; 2281 2282 static { 2283 try { 2284 stateOffset = unsafe.objectFieldOffset 2285 (AbstractQueuedSynchronizer.class.getDeclaredField("state")); 2286 headOffset = unsafe.objectFieldOffset 2287 (AbstractQueuedSynchronizer.class.getDeclaredField("head")); 2288 tailOffset = unsafe.objectFieldOffset 2289 (AbstractQueuedSynchronizer.class.getDeclaredField("tail")); 2290 waitStatusOffset = unsafe.objectFieldOffset 2291 (Node.class.getDeclaredField("waitStatus")); 2292 nextOffset = unsafe.objectFieldOffset 2293 (Node.class.getDeclaredField("next")); 2294 2295 } catch (Exception ex) { throw new Error(ex); } 2296 } 2297 2298 /** 2299 * CAS head field. Used only by enq. 2300 */ 2301 private final boolean compareAndSetHead(Node update) { 2302 return unsafe.compareAndSwapObject(this, headOffset, null, update); 2303 } 2304 2305 /** 2306 * CAS tail field. Used only by enq. 2307 */ 2308 private final boolean compareAndSetTail(Node expect, Node update) { 2309 return unsafe.compareAndSwapObject(this, tailOffset, expect, update); 2310 } 2311 2312 /** 2313 * CAS waitStatus field of a node. 2314 */ 2315 private static final boolean compareAndSetWaitStatus(Node node, 2316 int expect, 2317 int update) { 2318 return unsafe.compareAndSwapInt(node, waitStatusOffset, 2319 expect, update); 2320 } 2321 2322 /** 2323 * CAS next field of a node. 2324 */ 2325 private static final boolean compareAndSetNext(Node node, 2326 Node expect, 2327 Node update) { 2328 return unsafe.compareAndSwapObject(node, nextOffset, expect, update); 2329 } 2330 }
其中,共享锁源码相关的代码如下:
public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; // ReentrantReadWriteLock的AQS对象 private final Sync sync; protected ReadLock(ReentrantReadWriteLock lock) { sync = lock.sync; } // 获取“共享锁” public void lock() { sync.acquireShared(1); } // 如果线程是中断状态,则抛出一场,否则尝试获取共享锁。 public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } // 尝试获取“共享锁” public boolean tryLock() { return sync.tryReadLock(); } // 在指定时间内,尝试获取“共享锁” public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } // 释放“共享锁” public void unlock() { sync.releaseShared(1); } // 新建条件 public Condition newCondition() { throw new UnsupportedOperationException(); } public String toString() { int r = sync.getReadLockCount(); return super.toString() + "[Read locks = " + r + "]"; } }
说明:
ReadLock中的sync是一个Sync对象,Sync继承于AQS类,即Sync就是一个锁。ReentrantReadWriteLock中也有一个Sync对象,而且ReadLock中的sync和ReentrantReadWriteLock中的sync是对应关系。即ReentrantReadWriteLock和ReadLock共享同一个AQS对象,共享同一把锁。
ReentrantReadWriteLock中Sync的定义如下:
final Sync sync;
下面,分别从“获取共享锁”和“释放共享锁”两个方面对共享锁进行说明。
获取共享锁
获取共享锁的思想(即lock函数的步骤),是先通过tryAcquireShared()尝试获取共享锁。尝试成功的话,则直接返回;尝试失败的话,则通过doAcquireShared()不断的循环并尝试获取锁,若有需要,则阻塞等待。doAcquireShared()在循环中每次尝试获取锁时,都是通过tryAcquireShared()来进行尝试的。下面看看“获取共享锁”的详细流程。
1. lock()
lock()在ReadLock中,源码如下:
public void lock() { sync.acquireShared(1); }
2. acquireShared()
Sync继承于AQS,acquireShared()定义在AQS中。源码如下:
public final void acquireShared(int arg) { if (tryAcquireShared(arg) < 0) doAcquireShared(arg); }
说明:acquireShared()首先会通过tryAcquireShared()来尝试获取锁。
尝试成功的话,则不再做任何动作(因为已经成功获取到锁了)。
尝试失败的话,则通过doAcquireShared()来获取锁。doAcquireShared()会获取到锁了才返回。
3. tryAcquireShared()
tryAcquireShared()定义在ReentrantReadWriteLock.java的Sync中,源码如下:
protected final int tryAcquireShared(int unused) { Thread current = Thread.currentThread(); // 获取“锁”的状态 int c = getState(); // 如果“锁”是“互斥锁”,并且获取锁的线程不是current线程;则返回-1。 if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; // 获取“读取锁”的共享计数 int r = sharedCount(c); // 如果“不需要阻塞等待”,并且“读取锁”的共享计数小于MAX_COUNT; // 则通过CAS函数更新“锁的状态”,将“读取锁”的共享计数+1。 if (!readerShouldBlock() && r < MAX_COUNT && compareAndSetState(c, c + SHARED_UNIT)) { // 第1次获取“读取锁”。 if (r == 0) { firstReader = current; firstReaderHoldCount = 1; // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程 } else if (firstReader == current) { firstReaderHoldCount++; } else { // HoldCounter是用来统计该线程获取“读取锁”的次数。 HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) cachedHoldCounter = rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); // 将该线程获取“读取锁”的次数+1。 rh.count++; } return 1; } return fullTryAcquireShared(current); }
说明:tryAcquireShared()的作用是尝试获取“共享锁”。
如果在尝试获取锁时,“不需要阻塞等待”并且“读取锁的共享计数小于MAX_COUNT”,则直接通过CAS函数更新“读取锁的共享计数”,以及将“当前线程获取读取锁的次数+1”。
否则,通过fullTryAcquireShared()获取读取锁。
4. fullTryAcquireShared()
fullTryAcquireShared()在ReentrantReadWriteLock中定义,源码如下:
final int fullTryAcquireShared(Thread current) { HoldCounter rh = null; for (;;) { // 获取“锁”的状态 int c = getState(); // 如果“锁”是“互斥锁”,并且获取锁的线程不是current线程;则返回-1。 if (exclusiveCount(c) != 0) { if (getExclusiveOwnerThread() != current) return -1; // 如果“需要阻塞等待”。 // (01) 当“需要阻塞等待”的线程是第1个获取锁的线程的话,则继续往下执行。 // (02) 当“需要阻塞等待”的线程获取锁的次数=0时,则返回-1。 } else if (readerShouldBlock()) { // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程 if (firstReader == current) { } else { if (rh == null) { rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) { rh = readHolds.get(); if (rh.count == 0) readHolds.remove(); } } // 如果当前线程获取锁的计数=0,则返回-1。 if (rh.count == 0) return -1; } } // 如果“不需要阻塞等待”,则获取“读取锁”的共享统计数; // 如果共享统计数超过MAX_COUNT,则抛出异常。 if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); // 将线程获取“读取锁”的次数+1。 if (compareAndSetState(c, c + SHARED_UNIT)) { // 如果是第1次获取“读取锁”,则更新firstReader和firstReaderHoldCount。 if (sharedCount(c) == 0) { firstReader = current; firstReaderHoldCount = 1; // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程, // 则将firstReaderHoldCount+1。 } else if (firstReader == current) { firstReaderHoldCount++; } else { if (rh == null) rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); // 更新线程的获取“读取锁”的共享计数 rh.count++; cachedHoldCounter = rh; // cache for release } return 1; } } }
说明:fullTryAcquireShared()会根据“是否需要阻塞等待”,“读取锁的共享计数是否超过限制”等等进行处理。如果不需要阻塞等待,并且锁的共享计数没有超过限制,则通过CAS尝试获取锁,并返回1。
5. doAcquireShared()
doAcquireShared()定义在AQS函数中,源码如下:
private void doAcquireShared(int arg) { // addWaiter(Node.SHARED)的作用是,创建“当前线程”对应的节点,并将该线程添加到CLH队列中。 final Node node = addWaiter(Node.SHARED); boolean failed = true; try { boolean interrupted = false; for (;;) { // 获取“node”的前一节点 final Node p = node.predecessor(); // 如果“当前线程”是CLH队列的表头,则尝试获取共享锁。 if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC if (interrupted) selfInterrupt(); failed = false; return; } } // 如果“当前线程”不是CLH队列的表头,则通过shouldParkAfterFailedAcquire()判断是否需要等待, // 需要的话,则通过parkAndCheckInterrupt()进行阻塞等待。若阻塞等待过程中,线程被中断过,则设置interrupted为true。 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } }
说明:doAcquireShared()的作用是获取共享锁。
它会首先创建线程对应的CLH队列的节点,然后将该节点添加到CLH队列中。CLH队列是管理获取锁的等待线程的队列。
如果“当前线程”是CLH队列的表头,则尝试获取共享锁;否则,则需要通过shouldParkAfterFailedAcquire()判断是否阻塞等待,需要的话,则通过parkAndCheckInterrupt()进行阻塞等待。
doAcquireShared()会通过for循环,不断的进行上面的操作;目的就是获取共享锁。需要注意的是:doAcquireShared()在每一次尝试获取锁时,是通过tryAcquireShared()来执行的!
shouldParkAfterFailedAcquire(), parkAndCheckInterrupt()等函数已经在“Java多线程系列--“JUC锁”03之 公平锁(一) ”中详细介绍过,这里就不再重复说明了。
释放共享锁
释放共享锁的思想,是先通过tryReleaseShared()尝试释放共享锁。尝试成功的话,则通过doReleaseShared()唤醒“其他等待获取共享锁的线程”,并返回true;否则的话,返回flase。
1. unlock()
public void unlock() { sync.releaseShared(1); }
说明:该函数实际上调用releaseShared(1)释放共享锁。
2. releaseShared()
releaseShared()在AQS中实现,源码如下:
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; }
说明:releaseShared()的目的是让当前线程释放它所持有的共享锁。
它首先会通过tryReleaseShared()去尝试释放共享锁。尝试成功,则直接返回;尝试失败,则通过doReleaseShared()去释放共享锁。
3. tryReleaseShared()
tryReleaseShared()定义在ReentrantReadWriteLock中,源码如下:
protected final boolean tryReleaseShared(int unused) { // 获取当前线程,即释放共享锁的线程。 Thread current = Thread.currentThread(); // 如果想要释放锁的线程(current)是第1个获取锁(firstReader)的线程, // 并且“第1个获取锁的线程获取锁的次数”=1,则设置firstReader为null; // 否则,将“第1个获取锁的线程的获取次数”-1。 if (firstReader == current) { // assert firstReaderHoldCount > 0; if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; // 获取rh对象,并更新“当前线程获取锁的信息”。 } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); int count = rh.count; if (count <= 1) { readHolds.remove(); if (count <= 0) throw unmatchedUnlockException(); } --rh.count; } for (;;) { // 获取锁的状态 int c = getState(); // 将锁的获取次数-1。 int nextc = c - SHARED_UNIT; // 通过CAS更新锁的状态。 if (compareAndSetState(c, nextc)) return nextc == 0; } }
说明:tryReleaseShared()的作用是尝试释放共享锁。
4. doReleaseShared()
doReleaseShared()定义在AQS中,源码如下:
private void doReleaseShared() { for (;;) { // 获取CLH队列的头节点 Node h = head; // 如果头节点不为null,并且头节点不等于tail节点。 if (h != null && h != tail) { // 获取头节点对应的线程的状态 int ws = h.waitStatus; // 如果头节点对应的线程是SIGNAL状态,则意味着“头节点的下一个节点所对应的线程”需要被unpark唤醒。 if (ws == Node.SIGNAL) { // 设置“头节点对应的线程状态”为空状态。失败的话,则继续循环。 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // 唤醒“头节点的下一个节点所对应的线程”。 unparkSuccessor(h); } // 如果头节点对应的线程是空状态,则设置“文件点对应的线程所拥有的共享锁”为其它线程获取锁的空状态。 else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } // 如果头节点发生变化,则继续循环。否则,退出循环。 if (h == head) // loop if head changed break; } }
说明:doReleaseShared()会释放“共享锁”。它会从前往后的遍历CLH队列,依次“唤醒”然后“执行”队列中每个节点对应的线程;最终的目的是让这些线程释放它们所持有的锁。
公平共享锁和非公平共享锁
和互斥锁ReentrantLock一样,ReadLock也分为公平锁和非公平锁。
公平锁和非公平锁的区别,体现在判断是否需要阻塞的函数readerShouldBlock()是不同的。
公平锁的readerShouldBlock()的源码如下:
final boolean readerShouldBlock() { return hasQueuedPredecessors(); }
在公平共享锁中,如果在当前线程的前面有其他线程在等待获取共享锁,则返回true;否则,返回false。
非公平锁的readerShouldBlock()的源码如下:
final boolean readerShouldBlock() { return apparentlyFirstQueuedIsExclusive(); }
在非公平共享锁中,它会无视当前线程的前面是否有其他线程在等待获取共享锁。只要该非公平共享锁对应的线程不为null,则返回true。
ReentrantReadWriteLock示例
1 import java.util.concurrent.locks.ReadWriteLock; 2 import java.util.concurrent.locks.ReentrantReadWriteLock; 3 4 public class ReadWriteLockTest1 { 5 6 public static void main(String[] args) { 7 // 创建账户 8 MyCount myCount = new MyCount("4238920615242830", 10000); 9 // 创建用户,并指定账户 10 User user = new User("Tommy", myCount); 11 12 // 分别启动3个“读取账户金钱”的线程 和 3个“设置账户金钱”的线程 13 for (int i=0; i<3; i++) { 14 user.getCash(); 15 user.setCash((i+1)*1000); 16 } 17 } 18 } 19 20 class User { 21 private String name; //用户名 22 private MyCount myCount; //所要操作的账户 23 private ReadWriteLock myLock; //执行操作所需的锁对象 24 25 User(String name, MyCount myCount) { 26 this.name = name; 27 this.myCount = myCount; 28 this.myLock = new ReentrantReadWriteLock(); 29 } 30 31 public void getCash() { 32 new Thread() { 33 public void run() { 34 myLock.readLock().lock(); 35 try { 36 System.out.println(Thread.currentThread().getName() +" getCash start"); 37 myCount.getCash(); 38 Thread.sleep(1); 39 System.out.println(Thread.currentThread().getName() +" getCash end"); 40 } catch (InterruptedException e) { 41 } finally { 42 myLock.readLock().unlock(); 43 } 44 } 45 }.start(); 46 } 47 48 public void setCash(final int cash) { 49 new Thread() { 50 public void run() { 51 myLock.writeLock().lock(); 52 try { 53 System.out.println(Thread.currentThread().getName() +" setCash start"); 54 myCount.setCash(cash); 55 Thread.sleep(1); 56 System.out.println(Thread.currentThread().getName() +" setCash end"); 57 } catch (InterruptedException e) { 58 } finally { 59 myLock.writeLock().unlock(); 60 } 61 } 62 }.start(); 63 } 64 } 65 66 class MyCount { 67 private String id; //账号 68 private int cash; //账户余额 69 70 MyCount(String id, int cash) { 71 this.id = id; 72 this.cash = cash; 73 } 74 75 public String getId() { 76 return id; 77 } 78 79 public void setId(String id) { 80 this.id = id; 81 } 82 83 public int getCash() { 84 System.out.println(Thread.currentThread().getName() +" getCash cash="+ cash); 85 return cash; 86 } 87 88 public void setCash(int cash) { 89 System.out.println(Thread.currentThread().getName() +" setCash cash="+ cash); 90 this.cash = cash; 91 } 92 }
运行结果:
Thread-0 getCash start Thread-2 getCash start Thread-0 getCash cash=10000 Thread-2 getCash cash=10000 Thread-0 getCash end Thread-2 getCash end Thread-1 setCash start Thread-1 setCash cash=1000 Thread-1 setCash end Thread-3 setCash start Thread-3 setCash cash=2000 Thread-3 setCash end Thread-4 getCash start Thread-4 getCash cash=2000 Thread-4 getCash end Thread-5 setCash start Thread-5 setCash cash=3000 Thread-5 setCash end
结果说明:
(01) 观察Thread0和Thread-2的运行结果,我们发现,Thread-0启动并获取到“读取锁”,在它还没运行完毕的时候,Thread-2也启动了并且也成功获取到“读取锁”。
因此,“读取锁”支持被多个线程同时获取。
(02) 观察Thread-1,Thread-3,Thread-5这三个“写入锁”的线程。只要“写入锁”被某线程获取,则该线程运行完毕了,才释放该锁。
因此,“写入锁”不支持被多个线程同时获取。
概要
Java的JUC(java.util.concurrent)包中的锁包括"独占锁"和"共享锁"。在“Java多线程系列--“JUC锁”02之 互斥锁ReentrantLock ”中,对Java的独占锁进行了说明。本章对Java的“共享锁”进行介绍,JUC中的共享锁有CountDownLatch, CyclicBarrier, Semaphore, ReentrantReadWriteLock等;本章会以ReentrantReadWriteLock为蓝本对共享锁进行说明。内容包括:
ReadWriteLock 和 ReentrantReadWriteLock介绍
ReadWriteLock 和 ReentrantReadWriteLock函数列表
ReentrantReadWriteLock数据结构
参考代码(基于JDK1.7.0_40)
获取共享锁
释放共享锁
公平共享锁和非公平共享锁
ReentrantReadWriteLock示例
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3505809.html
ReadWriteLock 和 ReentrantReadWriteLock介绍
ReadWriteLock,顾名思义,是读写锁。它维护了一对相关的锁 — — “读取锁”和“写入锁”,一个用于读取操作,另一个用于写入操作。
“读取锁”用于只读操作,它是“共享锁”,能同时被多个线程获取。
“写入锁”用于写入操作,它是“独占锁”,写入锁只能被一个线程锁获取。
注意:不能同时存在读取锁和写入锁!
ReadWriteLock是一个接口。ReentrantReadWriteLock是它的实现类,ReentrantReadWriteLock包括子类ReadLock和WriteLock。
ReadWriteLock 和 ReentrantReadWriteLock函数列表
ReadWriteLock函数列表
// 返回用于读取操作的锁。 Lock readLock() // 返回用于写入操作的锁。 Lock writeLock()
// 创建一个新的 ReentrantReadWriteLock,默认是采用“非公平策略”。 ReentrantReadWriteLock() // 创建一个新的 ReentrantReadWriteLock,fair是“公平策略”。fair为true,意味着公平策略;否则,意味着非公平策略。 ReentrantReadWriteLock(boolean fair) // 返回当前拥有写入锁的线程,如果没有这样的线程,则返回 null。 protected Thread getOwner() // 返回一个 collection,它包含可能正在等待获取读取锁的线程。 protected Collection<Thread> getQueuedReaderThreads() // 返回一个 collection,它包含可能正在等待获取读取或写入锁的线程。 protected Collection<Thread> getQueuedThreads() // 返回一个 collection,它包含可能正在等待获取写入锁的线程。 protected Collection<Thread> getQueuedWriterThreads() // 返回等待获取读取或写入锁的线程估计数目。 int getQueueLength() // 查询当前线程在此锁上保持的重入读取锁数量。 int getReadHoldCount() // 查询为此锁保持的读取锁数量。 int getReadLockCount() // 返回一个 collection,它包含可能正在等待与写入锁相关的给定条件的那些线程。 protected Collection<Thread> getWaitingThreads(Condition condition) // 返回正等待与写入锁相关的给定条件的线程估计数目。 int getWaitQueueLength(Condition condition) // 查询当前线程在此锁上保持的重入写入锁数量。 int getWriteHoldCount() // 查询是否给定线程正在等待获取读取或写入锁。 boolean hasQueuedThread(Thread thread) // 查询是否所有的线程正在等待获取读取或写入锁。 boolean hasQueuedThreads() // 查询是否有些线程正在等待与写入锁有关的给定条件。 boolean hasWaiters(Condition condition) // 如果此锁将公平性设置为 ture,则返回 true。 boolean isFair() // 查询是否某个线程保持了写入锁。 boolean isWriteLocked() // 查询当前线程是否保持了写入锁。 boolean isWriteLockedByCurrentThread() // 返回用于读取操作的锁。 ReentrantReadWriteLock.ReadLock readLock() // 返回用于写入操作的锁。 ReentrantReadWriteLock.WriteLock writeLock()
ReentrantReadWriteLock数据结构
ReentrantReadWriteLock的UML类图如下:
从中可以看出:
(01) ReentrantReadWriteLock实现了ReadWriteLock接口。ReadWriteLock是一个读写锁的接口,提供了"获取读锁的readLock()函数" 和 "获取写锁的writeLock()函数"。
(02) ReentrantReadWriteLock中包含:sync对象,读锁readerLock和写锁writerLock。读锁ReadLock和写锁WriteLock都实现了Lock接口。读锁ReadLock和写锁WriteLock中也都分别包含了"Sync对象",它们的Sync对象和ReentrantReadWriteLock的Sync对象 是一样的,就是通过sync,读锁和写锁实现了对同一个对象的访问。
(03) 和"ReentrantLock"一样,sync是Sync类型;而且,Sync也是一个继承于AQS的抽象类。Sync也包括"公平锁"FairSync和"非公平锁"NonfairSync。sync对象是"FairSync"和"NonfairSync"中的一个,默认是"NonfairSync"。
参考代码(基于JDK1.7.0_40)
ReentrantReadWriteLock的完整源码
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /* 2 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 */ 24 25 /* 26 * 27 * 28 * 29 * 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.locks; 37 import java.util.concurrent.*; 38 import java.util.concurrent.atomic.*; 39 import java.util.*; 40 41 /** 42 * An implementation of {@link ReadWriteLock} supporting similar 43 * semantics to {@link ReentrantLock}. 44 * <p>This class has the following properties: 45 * 46 * <ul> 47 * <li><b>Acquisition order</b> 48 * 49 * <p> This class does not impose a reader or writer preference 50 * ordering for lock access. However, it does support an optional 51 * <em>fairness</em> policy. 52 * 53 * <dl> 54 * <dt><b><i>Non-fair mode (default)</i></b> 55 * <dd>When constructed as non-fair (the default), the order of entry 56 * to the read and write lock is unspecified, subject to reentrancy 57 * constraints. A nonfair lock that is continuously contended may 58 * indefinitely postpone one or more reader or writer threads, but 59 * will normally have higher throughput than a fair lock. 60 * <p> 61 * 62 * <dt><b><i>Fair mode</i></b> 63 * <dd> When constructed as fair, threads contend for entry using an 64 * approximately arrival-order policy. When the currently held lock 65 * is released either the longest-waiting single writer thread will 66 * be assigned the write lock, or if there is a group of reader threads 67 * waiting longer than all waiting writer threads, that group will be 68 * assigned the read lock. 69 * 70 * <p>A thread that tries to acquire a fair read lock (non-reentrantly) 71 * will block if either the write lock is held, or there is a waiting 72 * writer thread. The thread will not acquire the read lock until 73 * after the oldest currently waiting writer thread has acquired and 74 * released the write lock. Of course, if a waiting writer abandons 75 * its wait, leaving one or more reader threads as the longest waiters 76 * in the queue with the write lock free, then those readers will be 77 * assigned the read lock. 78 * 79 * <p>A thread that tries to acquire a fair write lock (non-reentrantly) 80 * will block unless both the read lock and write lock are free (which 81 * implies there are no waiting threads). (Note that the non-blocking 82 * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods 83 * do not honor this fair setting and will acquire the lock if it is 84 * possible, regardless of waiting threads.) 85 * <p> 86 * </dl> 87 * 88 * <li><b>Reentrancy</b> 89 * 90 * <p>This lock allows both readers and writers to reacquire read or 91 * write locks in the style of a {@link ReentrantLock}. Non-reentrant 92 * readers are not allowed until all write locks held by the writing 93 * thread have been released. 94 * 95 * <p>Additionally, a writer can acquire the read lock, but not 96 * vice-versa. Among other applications, reentrancy can be useful 97 * when write locks are held during calls or callbacks to methods that 98 * perform reads under read locks. If a reader tries to acquire the 99 * write lock it will never succeed. 100 * 101 * <li><b>Lock downgrading</b> 102 * <p>Reentrancy also allows downgrading from the write lock to a read lock, 103 * by acquiring the write lock, then the read lock and then releasing the 104 * write lock. However, upgrading from a read lock to the write lock is 105 * <b>not</b> possible. 106 * 107 * <li><b>Interruption of lock acquisition</b> 108 * <p>The read lock and write lock both support interruption during lock 109 * acquisition. 110 * 111 * <li><b>{@link Condition} support</b> 112 * <p>The write lock provides a {@link Condition} implementation that 113 * behaves in the same way, with respect to the write lock, as the 114 * {@link Condition} implementation provided by 115 * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}. 116 * This {@link Condition} can, of course, only be used with the write lock. 117 * 118 * <p>The read lock does not support a {@link Condition} and 119 * {@code readLock().newCondition()} throws 120 * {@code UnsupportedOperationException}. 121 * 122 * <li><b>Instrumentation</b> 123 * <p>This class supports methods to determine whether locks 124 * are held or contended. These methods are designed for monitoring 125 * system state, not for synchronization control. 126 * </ul> 127 * 128 * <p>Serialization of this class behaves in the same way as built-in 129 * locks: a deserialized lock is in the unlocked state, regardless of 130 * its state when serialized. 131 * 132 * <p><b>Sample usages</b>. Here is a code sketch showing how to perform 133 * lock downgrading after updating a cache (exception handling is 134 * particularly tricky when handling multiple locks in a non-nested 135 * fashion): 136 * 137 * <pre> {@code 138 * class CachedData { 139 * Object data; 140 * volatile boolean cacheValid; 141 * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); 142 * 143 * void processCachedData() { 144 * rwl.readLock().lock(); 145 * if (!cacheValid) { 146 * // Must release read lock before acquiring write lock 147 * rwl.readLock().unlock(); 148 * rwl.writeLock().lock(); 149 * try { 150 * // Recheck state because another thread might have 151 * // acquired write lock and changed state before we did. 152 * if (!cacheValid) { 153 * data = ... 154 * cacheValid = true; 155 * } 156 * // Downgrade by acquiring read lock before releasing write lock 157 * rwl.readLock().lock(); 158 * } finally { 159 * rwl.writeLock().unlock(); // Unlock write, still hold read 160 * } 161 * } 162 * 163 * try { 164 * use(data); 165 * } finally { 166 * rwl.readLock().unlock(); 167 * } 168 * } 169 * }}</pre> 170 * 171 * ReentrantReadWriteLocks can be used to improve concurrency in some 172 * uses of some kinds of Collections. This is typically worthwhile 173 * only when the collections are expected to be large, accessed by 174 * more reader threads than writer threads, and entail operations with 175 * overhead that outweighs synchronization overhead. For example, here 176 * is a class using a TreeMap that is expected to be large and 177 * concurrently accessed. 178 * 179 * <pre>{@code 180 * class RWDictionary { 181 * private final Map<String, Data> m = new TreeMap<String, Data>(); 182 * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); 183 * private final Lock r = rwl.readLock(); 184 * private final Lock w = rwl.writeLock(); 185 * 186 * public Data get(String key) { 187 * r.lock(); 188 * try { return m.get(key); } 189 * finally { r.unlock(); } 190 * } 191 * public String[] allKeys() { 192 * r.lock(); 193 * try { return m.keySet().toArray(); } 194 * finally { r.unlock(); } 195 * } 196 * public Data put(String key, Data value) { 197 * w.lock(); 198 * try { return m.put(key, value); } 199 * finally { w.unlock(); } 200 * } 201 * public void clear() { 202 * w.lock(); 203 * try { m.clear(); } 204 * finally { w.unlock(); } 205 * } 206 * }}</pre> 207 * 208 * <h3>Implementation Notes</h3> 209 * 210 * <p>This lock supports a maximum of 65535 recursive write locks 211 * and 65535 read locks. Attempts to exceed these limits result in 212 * {@link Error} throws from locking methods. 213 * 214 * @since 1.5 215 * @author Doug Lea 216 * 217 */ 218 public class ReentrantReadWriteLock 219 implements ReadWriteLock, java.io.Serializable { 220 private static final long serialVersionUID = -6992448646407690164L; 221 /** Inner class providing readlock */ 222 private final ReentrantReadWriteLock.ReadLock readerLock; 223 /** Inner class providing writelock */ 224 private final ReentrantReadWriteLock.WriteLock writerLock; 225 /** Performs all synchronization mechanics */ 226 final Sync sync; 227 228 /** 229 * Creates a new {@code ReentrantReadWriteLock} with 230 * default (nonfair) ordering properties. 231 */ 232 public ReentrantReadWriteLock() { 233 this(false); 234 } 235 236 /** 237 * Creates a new {@code ReentrantReadWriteLock} with 238 * the given fairness policy. 239 * 240 * @param fair {@code true} if this lock should use a fair ordering policy 241 */ 242 public ReentrantReadWriteLock(boolean fair) { 243 sync = fair ? new FairSync() : new NonfairSync(); 244 readerLock = new ReadLock(this); 245 writerLock = new WriteLock(this); 246 } 247 248 public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; } 249 public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; } 250 251 /** 252 * Synchronization implementation for ReentrantReadWriteLock. 253 * Subclassed into fair and nonfair versions. 254 */ 255 abstract static class Sync extends AbstractQueuedSynchronizer { 256 private static final long serialVersionUID = 6317671515068378041L; 257 258 /* 259 * Read vs write count extraction constants and functions. 260 * Lock state is logically divided into two unsigned shorts: 261 * The lower one representing the exclusive (writer) lock hold count, 262 * and the upper the shared (reader) hold count. 263 */ 264 265 static final int SHARED_SHIFT = 16; 266 static final int SHARED_UNIT = (1 << SHARED_SHIFT); 267 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; 268 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; 269 270 /** Returns the number of shared holds represented in count */ 271 static int sharedCount(int c) { return c >>> SHARED_SHIFT; } 272 /** Returns the number of exclusive holds represented in count */ 273 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } 274 275 /** 276 * A counter for per-thread read hold counts. 277 * Maintained as a ThreadLocal; cached in cachedHoldCounter 278 */ 279 static final class HoldCounter { 280 int count = 0; 281 // Use id, not reference, to avoid garbage retention 282 final long tid = Thread.currentThread().getId(); 283 } 284 285 /** 286 * ThreadLocal subclass. Easiest to explicitly define for sake 287 * of deserialization mechanics. 288 */ 289 static final class ThreadLocalHoldCounter 290 extends ThreadLocal<HoldCounter> { 291 public HoldCounter initialValue() { 292 return new HoldCounter(); 293 } 294 } 295 296 /** 297 * The number of reentrant read locks held by current thread. 298 * Initialized only in constructor and readObject. 299 * Removed whenever a thread's read hold count drops to 0. 300 */ 301 private transient ThreadLocalHoldCounter readHolds; 302 303 /** 304 * The hold count of the last thread to successfully acquire 305 * readLock. This saves ThreadLocal lookup in the common case 306 * where the next thread to release is the last one to 307 * acquire. This is non-volatile since it is just used 308 * as a heuristic, and would be great for threads to cache. 309 * 310 * <p>Can outlive the Thread for which it is caching the read 311 * hold count, but avoids garbage retention by not retaining a 312 * reference to the Thread. 313 * 314 * <p>Accessed via a benign data race; relies on the memory 315 * model's final field and out-of-thin-air guarantees. 316 */ 317 private transient HoldCounter cachedHoldCounter; 318 319 /** 320 * firstReader is the first thread to have acquired the read lock. 321 * firstReaderHoldCount is firstReader's hold count. 322 * 323 * <p>More precisely, firstReader is the unique thread that last 324 * changed the shared count from 0 to 1, and has not released the 325 * read lock since then; null if there is no such thread. 326 * 327 * <p>Cannot cause garbage retention unless the thread terminated 328 * without relinquishing its read locks, since tryReleaseShared 329 * sets it to null. 330 * 331 * <p>Accessed via a benign data race; relies on the memory 332 * model's out-of-thin-air guarantees for references. 333 * 334 * <p>This allows tracking of read holds for uncontended read 335 * locks to be very cheap. 336 */ 337 private transient Thread firstReader = null; 338 private transient int firstReaderHoldCount; 339 340 Sync() { 341 readHolds = new ThreadLocalHoldCounter(); 342 setState(getState()); // ensures visibility of readHolds 343 } 344 345 /* 346 * Acquires and releases use the same code for fair and 347 * nonfair locks, but differ in whether/how they allow barging 348 * when queues are non-empty. 349 */ 350 351 /** 352 * Returns true if the current thread, when trying to acquire 353 * the read lock, and otherwise eligible to do so, should block 354 * because of policy for overtaking other waiting threads. 355 */ 356 abstract boolean readerShouldBlock(); 357 358 /** 359 * Returns true if the current thread, when trying to acquire 360 * the write lock, and otherwise eligible to do so, should block 361 * because of policy for overtaking other waiting threads. 362 */ 363 abstract boolean writerShouldBlock(); 364 365 /* 366 * Note that tryRelease and tryAcquire can be called by 367 * Conditions. So it is possible that their arguments contain 368 * both read and write holds that are all released during a 369 * condition wait and re-established in tryAcquire. 370 */ 371 372 protected final boolean tryRelease(int releases) { 373 if (!isHeldExclusively()) 374 throw new IllegalMonitorStateException(); 375 int nextc = getState() - releases; 376 boolean free = exclusiveCount(nextc) == 0; 377 if (free) 378 setExclusiveOwnerThread(null); 379 setState(nextc); 380 return free; 381 } 382 383 protected final boolean tryAcquire(int acquires) { 384 /* 385 * Walkthrough: 386 * 1. If read count nonzero or write count nonzero 387 * and owner is a different thread, fail. 388 * 2. If count would saturate, fail. (This can only 389 * happen if count is already nonzero.) 390 * 3. Otherwise, this thread is eligible for lock if 391 * it is either a reentrant acquire or 392 * queue policy allows it. If so, update state 393 * and set owner. 394 */ 395 Thread current = Thread.currentThread(); 396 int c = getState(); 397 int w = exclusiveCount(c); 398 if (c != 0) { 399 // (Note: if c != 0 and w == 0 then shared count != 0) 400 if (w == 0 || current != getExclusiveOwnerThread()) 401 return false; 402 if (w + exclusiveCount(acquires) > MAX_COUNT) 403 throw new Error("Maximum lock count exceeded"); 404 // Reentrant acquire 405 setState(c + acquires); 406 return true; 407 } 408 if (writerShouldBlock() || 409 !compareAndSetState(c, c + acquires)) 410 return false; 411 setExclusiveOwnerThread(current); 412 return true; 413 } 414 415 protected final boolean tryReleaseShared(int unused) { 416 Thread current = Thread.currentThread(); 417 if (firstReader == current) { 418 // assert firstReaderHoldCount > 0; 419 if (firstReaderHoldCount == 1) 420 firstReader = null; 421 else 422 firstReaderHoldCount--; 423 } else { 424 HoldCounter rh = cachedHoldCounter; 425 if (rh == null || rh.tid != current.getId()) 426 rh = readHolds.get(); 427 int count = rh.count; 428 if (count <= 1) { 429 readHolds.remove(); 430 if (count <= 0) 431 throw unmatchedUnlockException(); 432 } 433 --rh.count; 434 } 435 for (;;) { 436 int c = getState(); 437 int nextc = c - SHARED_UNIT; 438 if (compareAndSetState(c, nextc)) 439 // Releasing the read lock has no effect on readers, 440 // but it may allow waiting writers to proceed if 441 // both read and write locks are now free. 442 return nextc == 0; 443 } 444 } 445 446 private IllegalMonitorStateException unmatchedUnlockException() { 447 return new IllegalMonitorStateException( 448 "attempt to unlock read lock, not locked by current thread"); 449 } 450 451 protected final int tryAcquireShared(int unused) { 452 /* 453 * Walkthrough: 454 * 1. If write lock held by another thread, fail. 455 * 2. Otherwise, this thread is eligible for 456 * lock wrt state, so ask if it should block 457 * because of queue policy. If not, try 458 * to grant by CASing state and updating count. 459 * Note that step does not check for reentrant 460 * acquires, which is postponed to full version 461 * to avoid having to check hold count in 462 * the more typical non-reentrant case. 463 * 3. If step 2 fails either because thread 464 * apparently not eligible or CAS fails or count 465 * saturated, chain to version with full retry loop. 466 */ 467 Thread current = Thread.currentThread(); 468 int c = getState(); 469 if (exclusiveCount(c) != 0 && 470 getExclusiveOwnerThread() != current) 471 return -1; 472 int r = sharedCount(c); 473 if (!readerShouldBlock() && 474 r < MAX_COUNT && 475 compareAndSetState(c, c + SHARED_UNIT)) { 476 if (r == 0) { 477 firstReader = current; 478 firstReaderHoldCount = 1; 479 } else if (firstReader == current) { 480 firstReaderHoldCount++; 481 } else { 482 HoldCounter rh = cachedHoldCounter; 483 if (rh == null || rh.tid != current.getId()) 484 cachedHoldCounter = rh = readHolds.get(); 485 else if (rh.count == 0) 486 readHolds.set(rh); 487 rh.count++; 488 } 489 return 1; 490 } 491 return fullTryAcquireShared(current); 492 } 493 494 /** 495 * Full version of acquire for reads, that handles CAS misses 496 * and reentrant reads not dealt with in tryAcquireShared. 497 */ 498 final int fullTryAcquireShared(Thread current) { 499 /* 500 * This code is in part redundant with that in 501 * tryAcquireShared but is simpler overall by not 502 * complicating tryAcquireShared with interactions between 503 * retries and lazily reading hold counts. 504 */ 505 HoldCounter rh = null; 506 for (;;) { 507 int c = getState(); 508 if (exclusiveCount(c) != 0) { 509 if (getExclusiveOwnerThread() != current) 510 return -1; 511 // else we hold the exclusive lock; blocking here 512 // would cause deadlock. 513 } else if (readerShouldBlock()) { 514 // Make sure we're not acquiring read lock reentrantly 515 if (firstReader == current) { 516 // assert firstReaderHoldCount > 0; 517 } else { 518 if (rh == null) { 519 rh = cachedHoldCounter; 520 if (rh == null || rh.tid != current.getId()) { 521 rh = readHolds.get(); 522 if (rh.count == 0) 523 readHolds.remove(); 524 } 525 } 526 if (rh.count == 0) 527 return -1; 528 } 529 } 530 if (sharedCount(c) == MAX_COUNT) 531 throw new Error("Maximum lock count exceeded"); 532 if (compareAndSetState(c, c + SHARED_UNIT)) { 533 if (sharedCount(c) == 0) { 534 firstReader = current; 535 firstReaderHoldCount = 1; 536 } else if (firstReader == current) { 537 firstReaderHoldCount++; 538 } else { 539 if (rh == null) 540 rh = cachedHoldCounter; 541 if (rh == null || rh.tid != current.getId()) 542 rh = readHolds.get(); 543 else if (rh.count == 0) 544 readHolds.set(rh); 545 rh.count++; 546 cachedHoldCounter = rh; // cache for release 547 } 548 return 1; 549 } 550 } 551 } 552 553 /** 554 * Performs tryLock for write, enabling barging in both modes. 555 * This is identical in effect to tryAcquire except for lack 556 * of calls to writerShouldBlock. 557 */ 558 final boolean tryWriteLock() { 559 Thread current = Thread.currentThread(); 560 int c = getState(); 561 if (c != 0) { 562 int w = exclusiveCount(c); 563 if (w == 0 || current != getExclusiveOwnerThread()) 564 return false; 565 if (w == MAX_COUNT) 566 throw new Error("Maximum lock count exceeded"); 567 } 568 if (!compareAndSetState(c, c + 1)) 569 return false; 570 setExclusiveOwnerThread(current); 571 return true; 572 } 573 574 /** 575 * Performs tryLock for read, enabling barging in both modes. 576 * This is identical in effect to tryAcquireShared except for 577 * lack of calls to readerShouldBlock. 578 */ 579 final boolean tryReadLock() { 580 Thread current = Thread.currentThread(); 581 for (;;) { 582 int c = getState(); 583 if (exclusiveCount(c) != 0 && 584 getExclusiveOwnerThread() != current) 585 return false; 586 int r = sharedCount(c); 587 if (r == MAX_COUNT) 588 throw new Error("Maximum lock count exceeded"); 589 if (compareAndSetState(c, c + SHARED_UNIT)) { 590 if (r == 0) { 591 firstReader = current; 592 firstReaderHoldCount = 1; 593 } else if (firstReader == current) { 594 firstReaderHoldCount++; 595 } else { 596 HoldCounter rh = cachedHoldCounter; 597 if (rh == null || rh.tid != current.getId()) 598 cachedHoldCounter = rh = readHolds.get(); 599 else if (rh.count == 0) 600 readHolds.set(rh); 601 rh.count++; 602 } 603 return true; 604 } 605 } 606 } 607 608 protected final boolean isHeldExclusively() { 609 // While we must in general read state before owner, 610 // we don't need to do so to check if current thread is owner 611 return getExclusiveOwnerThread() == Thread.currentThread(); 612 } 613 614 // Methods relayed to outer class 615 616 final ConditionObject newCondition() { 617 return new ConditionObject(); 618 } 619 620 final Thread getOwner() { 621 // Must read state before owner to ensure memory consistency 622 return ((exclusiveCount(getState()) == 0) ? 623 null : 624 getExclusiveOwnerThread()); 625 } 626 627 final int getReadLockCount() { 628 return sharedCount(getState()); 629 } 630 631 final boolean isWriteLocked() { 632 return exclusiveCount(getState()) != 0; 633 } 634 635 final int getWriteHoldCount() { 636 return isHeldExclusively() ? exclusiveCount(getState()) : 0; 637 } 638 639 final int getReadHoldCount() { 640 if (getReadLockCount() == 0) 641 return 0; 642 643 Thread current = Thread.currentThread(); 644 if (firstReader == current) 645 return firstReaderHoldCount; 646 647 HoldCounter rh = cachedHoldCounter; 648 if (rh != null && rh.tid == current.getId()) 649 return rh.count; 650 651 int count = readHolds.get().count; 652 if (count == 0) readHolds.remove(); 653 return count; 654 } 655 656 /** 657 * Reconstitute this lock instance from a stream 658 * @param s the stream 659 */ 660 private void readObject(java.io.ObjectInputStream s) 661 throws java.io.IOException, ClassNotFoundException { 662 s.defaultReadObject(); 663 readHolds = new ThreadLocalHoldCounter(); 664 setState(0); // reset to unlocked state 665 } 666 667 final int getCount() { return getState(); } 668 } 669 670 /** 671 * Nonfair version of Sync 672 */ 673 static final class NonfairSync extends Sync { 674 private static final long serialVersionUID = -8159625535654395037L; 675 final boolean writerShouldBlock() { 676 return false; // writers can always barge 677 } 678 final boolean readerShouldBlock() { 679 /* As a heuristic to avoid indefinite writer starvation, 680 * block if the thread that momentarily appears to be head 681 * of queue, if one exists, is a waiting writer. This is 682 * only a probabilistic effect since a new reader will not 683 * block if there is a waiting writer behind other enabled 684 * readers that have not yet drained from the queue. 685 */ 686 return apparentlyFirstQueuedIsExclusive(); 687 } 688 } 689 690 /** 691 * Fair version of Sync 692 */ 693 static final class FairSync extends Sync { 694 private static final long serialVersionUID = -2274990926593161451L; 695 final boolean writerShouldBlock() { 696 return hasQueuedPredecessors(); 697 } 698 final boolean readerShouldBlock() { 699 return hasQueuedPredecessors(); 700 } 701 } 702 703 /** 704 * The lock returned by method {@link ReentrantReadWriteLock#readLock}. 705 */ 706 public static class ReadLock implements Lock, java.io.Serializable { 707 private static final long serialVersionUID = -5992448646407690164L; 708 private final Sync sync; 709 710 /** 711 * Constructor for use by subclasses 712 * 713 * @param lock the outer lock object 714 * @throws NullPointerException if the lock is null 715 */ 716 protected ReadLock(ReentrantReadWriteLock lock) { 717 sync = lock.sync; 718 } 719 720 /** 721 * Acquires the read lock. 722 * 723 * <p>Acquires the read lock if the write lock is not held by 724 * another thread and returns immediately. 725 * 726 * <p>If the write lock is held by another thread then 727 * the current thread becomes disabled for thread scheduling 728 * purposes and lies dormant until the read lock has been acquired. 729 */ 730 public void lock() { 731 sync.acquireShared(1); 732 } 733 734 /** 735 * Acquires the read lock unless the current thread is 736 * {@linkplain Thread#interrupt interrupted}. 737 * 738 * <p>Acquires the read lock if the write lock is not held 739 * by another thread and returns immediately. 740 * 741 * <p>If the write lock is held by another thread then the 742 * current thread becomes disabled for thread scheduling 743 * purposes and lies dormant until one of two things happens: 744 * 745 * <ul> 746 * 747 * <li>The read lock is acquired by the current thread; or 748 * 749 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 750 * the current thread. 751 * 752 * </ul> 753 * 754 * <p>If the current thread: 755 * 756 * <ul> 757 * 758 * <li>has its interrupted status set on entry to this method; or 759 * 760 * <li>is {@linkplain Thread#interrupt interrupted} while 761 * acquiring the read lock, 762 * 763 * </ul> 764 * 765 * then {@link InterruptedException} is thrown and the current 766 * thread's interrupted status is cleared. 767 * 768 * <p>In this implementation, as this method is an explicit 769 * interruption point, preference is given to responding to 770 * the interrupt over normal or reentrant acquisition of the 771 * lock. 772 * 773 * @throws InterruptedException if the current thread is interrupted 774 */ 775 public void lockInterruptibly() throws InterruptedException { 776 sync.acquireSharedInterruptibly(1); 777 } 778 779 /** 780 * Acquires the read lock only if the write lock is not held by 781 * another thread at the time of invocation. 782 * 783 * <p>Acquires the read lock if the write lock is not held by 784 * another thread and returns immediately with the value 785 * {@code true}. Even when this lock has been set to use a 786 * fair ordering policy, a call to {@code tryLock()} 787 * <em>will</em> immediately acquire the read lock if it is 788 * available, whether or not other threads are currently 789 * waiting for the read lock. This "barging" behavior 790 * can be useful in certain circumstances, even though it 791 * breaks fairness. If you want to honor the fairness setting 792 * for this lock, then use {@link #tryLock(long, TimeUnit) 793 * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent 794 * (it also detects interruption). 795 * 796 * <p>If the write lock is held by another thread then 797 * this method will return immediately with the value 798 * {@code false}. 799 * 800 * @return {@code true} if the read lock was acquired 801 */ 802 public boolean tryLock() { 803 return sync.tryReadLock(); 804 } 805 806 /** 807 * Acquires the read lock if the write lock is not held by 808 * another thread within the given waiting time and the 809 * current thread has not been {@linkplain Thread#interrupt 810 * interrupted}. 811 * 812 * <p>Acquires the read lock if the write lock is not held by 813 * another thread and returns immediately with the value 814 * {@code true}. If this lock has been set to use a fair 815 * ordering policy then an available lock <em>will not</em> be 816 * acquired if any other threads are waiting for the 817 * lock. This is in contrast to the {@link #tryLock()} 818 * method. If you want a timed {@code tryLock} that does 819 * permit barging on a fair lock then combine the timed and 820 * un-timed forms together: 821 * 822 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } 823 * </pre> 824 * 825 * <p>If the write lock is held by another thread then the 826 * current thread becomes disabled for thread scheduling 827 * purposes and lies dormant until one of three things happens: 828 * 829 * <ul> 830 * 831 * <li>The read lock is acquired by the current thread; or 832 * 833 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 834 * the current thread; or 835 * 836 * <li>The specified waiting time elapses. 837 * 838 * </ul> 839 * 840 * <p>If the read lock is acquired then the value {@code true} is 841 * returned. 842 * 843 * <p>If the current thread: 844 * 845 * <ul> 846 * 847 * <li>has its interrupted status set on entry to this method; or 848 * 849 * <li>is {@linkplain Thread#interrupt interrupted} while 850 * acquiring the read lock, 851 * 852 * </ul> then {@link InterruptedException} is thrown and the 853 * current thread's interrupted status is cleared. 854 * 855 * <p>If the specified waiting time elapses then the value 856 * {@code false} is returned. If the time is less than or 857 * equal to zero, the method will not wait at all. 858 * 859 * <p>In this implementation, as this method is an explicit 860 * interruption point, preference is given to responding to 861 * the interrupt over normal or reentrant acquisition of the 862 * lock, and over reporting the elapse of the waiting time. 863 * 864 * @param timeout the time to wait for the read lock 865 * @param unit the time unit of the timeout argument 866 * @return {@code true} if the read lock was acquired 867 * @throws InterruptedException if the current thread is interrupted 868 * @throws NullPointerException if the time unit is null 869 * 870 */ 871 public boolean tryLock(long timeout, TimeUnit unit) 872 throws InterruptedException { 873 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 874 } 875 876 /** 877 * Attempts to release this lock. 878 * 879 * <p> If the number of readers is now zero then the lock 880 * is made available for write lock attempts. 881 */ 882 public void unlock() { 883 sync.releaseShared(1); 884 } 885 886 /** 887 * Throws {@code UnsupportedOperationException} because 888 * {@code ReadLocks} do not support conditions. 889 * 890 * @throws UnsupportedOperationException always 891 */ 892 public Condition newCondition() { 893 throw new UnsupportedOperationException(); 894 } 895 896 /** 897 * Returns a string identifying this lock, as well as its lock state. 898 * The state, in brackets, includes the String {@code "Read locks ="} 899 * followed by the number of held read locks. 900 * 901 * @return a string identifying this lock, as well as its lock state 902 */ 903 public String toString() { 904 int r = sync.getReadLockCount(); 905 return super.toString() + 906 "[Read locks = " + r + "]"; 907 } 908 } 909 910 /** 911 * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. 912 */ 913 public static class WriteLock implements Lock, java.io.Serializable { 914 private static final long serialVersionUID = -4992448646407690164L; 915 private final Sync sync; 916 917 /** 918 * Constructor for use by subclasses 919 * 920 * @param lock the outer lock object 921 * @throws NullPointerException if the lock is null 922 */ 923 protected WriteLock(ReentrantReadWriteLock lock) { 924 sync = lock.sync; 925 } 926 927 /** 928 * Acquires the write lock. 929 * 930 * <p>Acquires the write lock if neither the read nor write lock 931 * are held by another thread 932 * and returns immediately, setting the write lock hold count to 933 * one. 934 * 935 * <p>If the current thread already holds the write lock then the 936 * hold count is incremented by one and the method returns 937 * immediately. 938 * 939 * <p>If the lock is held by another thread then the current 940 * thread becomes disabled for thread scheduling purposes and 941 * lies dormant until the write lock has been acquired, at which 942 * time the write lock hold count is set to one. 943 */ 944 public void lock() { 945 sync.acquire(1); 946 } 947 948 /** 949 * Acquires the write lock unless the current thread is 950 * {@linkplain Thread#interrupt interrupted}. 951 * 952 * <p>Acquires the write lock if neither the read nor write lock 953 * are held by another thread 954 * and returns immediately, setting the write lock hold count to 955 * one. 956 * 957 * <p>If the current thread already holds this lock then the 958 * hold count is incremented by one and the method returns 959 * immediately. 960 * 961 * <p>If the lock is held by another thread then the current 962 * thread becomes disabled for thread scheduling purposes and 963 * lies dormant until one of two things happens: 964 * 965 * <ul> 966 * 967 * <li>The write lock is acquired by the current thread; or 968 * 969 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 970 * the current thread. 971 * 972 * </ul> 973 * 974 * <p>If the write lock is acquired by the current thread then the 975 * lock hold count is set to one. 976 * 977 * <p>If the current thread: 978 * 979 * <ul> 980 * 981 * <li>has its interrupted status set on entry to this method; 982 * or 983 * 984 * <li>is {@linkplain Thread#interrupt interrupted} while 985 * acquiring the write lock, 986 * 987 * </ul> 988 * 989 * then {@link InterruptedException} is thrown and the current 990 * thread's interrupted status is cleared. 991 * 992 * <p>In this implementation, as this method is an explicit 993 * interruption point, preference is given to responding to 994 * the interrupt over normal or reentrant acquisition of the 995 * lock. 996 * 997 * @throws InterruptedException if the current thread is interrupted 998 */ 999 public void lockInterruptibly() throws InterruptedException { 1000 sync.acquireInterruptibly(1); 1001 } 1002 1003 /** 1004 * Acquires the write lock only if it is not held by another thread 1005 * at the time of invocation. 1006 * 1007 * <p>Acquires the write lock if neither the read nor write lock 1008 * are held by another thread 1009 * and returns immediately with the value {@code true}, 1010 * setting the write lock hold count to one. Even when this lock has 1011 * been set to use a fair ordering policy, a call to 1012 * {@code tryLock()} <em>will</em> immediately acquire the 1013 * lock if it is available, whether or not other threads are 1014 * currently waiting for the write lock. This "barging" 1015 * behavior can be useful in certain circumstances, even 1016 * though it breaks fairness. If you want to honor the 1017 * fairness setting for this lock, then use {@link 1018 * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } 1019 * which is almost equivalent (it also detects interruption). 1020 * 1021 * <p> If the current thread already holds this lock then the 1022 * hold count is incremented by one and the method returns 1023 * {@code true}. 1024 * 1025 * <p>If the lock is held by another thread then this method 1026 * will return immediately with the value {@code false}. 1027 * 1028 * @return {@code true} if the lock was free and was acquired 1029 * by the current thread, or the write lock was already held 1030 * by the current thread; and {@code false} otherwise. 1031 */ 1032 public boolean tryLock( ) { 1033 return sync.tryWriteLock(); 1034 } 1035 1036 /** 1037 * Acquires the write lock if it is not held by another thread 1038 * within the given waiting time and the current thread has 1039 * not been {@linkplain Thread#interrupt interrupted}. 1040 * 1041 * <p>Acquires the write lock if neither the read nor write lock 1042 * are held by another thread 1043 * and returns immediately with the value {@code true}, 1044 * setting the write lock hold count to one. If this lock has been 1045 * set to use a fair ordering policy then an available lock 1046 * <em>will not</em> be acquired if any other threads are 1047 * waiting for the write lock. This is in contrast to the {@link 1048 * #tryLock()} method. If you want a timed {@code tryLock} 1049 * that does permit barging on a fair lock then combine the 1050 * timed and un-timed forms together: 1051 * 1052 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } 1053 * </pre> 1054 * 1055 * <p>If the current thread already holds this lock then the 1056 * hold count is incremented by one and the method returns 1057 * {@code true}. 1058 * 1059 * <p>If the lock is held by another thread then the current 1060 * thread becomes disabled for thread scheduling purposes and 1061 * lies dormant until one of three things happens: 1062 * 1063 * <ul> 1064 * 1065 * <li>The write lock is acquired by the current thread; or 1066 * 1067 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 1068 * the current thread; or 1069 * 1070 * <li>The specified waiting time elapses 1071 * 1072 * </ul> 1073 * 1074 * <p>If the write lock is acquired then the value {@code true} is 1075 * returned and the write lock hold count is set to one. 1076 * 1077 * <p>If the current thread: 1078 * 1079 * <ul> 1080 * 1081 * <li>has its interrupted status set on entry to this method; 1082 * or 1083 * 1084 * <li>is {@linkplain Thread#interrupt interrupted} while 1085 * acquiring the write lock, 1086 * 1087 * </ul> 1088 * 1089 * then {@link InterruptedException} is thrown and the current 1090 * thread's interrupted status is cleared. 1091 * 1092 * <p>If the specified waiting time elapses then the value 1093 * {@code false} is returned. If the time is less than or 1094 * equal to zero, the method will not wait at all. 1095 * 1096 * <p>In this implementation, as this method is an explicit 1097 * interruption point, preference is given to responding to 1098 * the interrupt over normal or reentrant acquisition of the 1099 * lock, and over reporting the elapse of the waiting time. 1100 * 1101 * @param timeout the time to wait for the write lock 1102 * @param unit the time unit of the timeout argument 1103 * 1104 * @return {@code true} if the lock was free and was acquired 1105 * by the current thread, or the write lock was already held by the 1106 * current thread; and {@code false} if the waiting time 1107 * elapsed before the lock could be acquired. 1108 * 1109 * @throws InterruptedException if the current thread is interrupted 1110 * @throws NullPointerException if the time unit is null 1111 * 1112 */ 1113 public boolean tryLock(long timeout, TimeUnit unit) 1114 throws InterruptedException { 1115 return sync.tryAcquireNanos(1, unit.toNanos(timeout)); 1116 } 1117 1118 /** 1119 * Attempts to release this lock. 1120 * 1121 * <p>If the current thread is the holder of this lock then 1122 * the hold count is decremented. If the hold count is now 1123 * zero then the lock is released. If the current thread is 1124 * not the holder of this lock then {@link 1125 * IllegalMonitorStateException} is thrown. 1126 * 1127 * @throws IllegalMonitorStateException if the current thread does not 1128 * hold this lock. 1129 */ 1130 public void unlock() { 1131 sync.release(1); 1132 } 1133 1134 /** 1135 * Returns a {@link Condition} instance for use with this 1136 * {@link Lock} instance. 1137 * <p>The returned {@link Condition} instance supports the same 1138 * usages as do the {@link Object} monitor methods ({@link 1139 * Object#wait() wait}, {@link Object#notify notify}, and {@link 1140 * Object#notifyAll notifyAll}) when used with the built-in 1141 * monitor lock. 1142 * 1143 * <ul> 1144 * 1145 * <li>If this write lock is not held when any {@link 1146 * Condition} method is called then an {@link 1147 * IllegalMonitorStateException} is thrown. (Read locks are 1148 * held independently of write locks, so are not checked or 1149 * affected. However it is essentially always an error to 1150 * invoke a condition waiting method when the current thread 1151 * has also acquired read locks, since other threads that 1152 * could unblock it will not be able to acquire the write 1153 * lock.) 1154 * 1155 * <li>When the condition {@linkplain Condition#await() waiting} 1156 * methods are called the write lock is released and, before 1157 * they return, the write lock is reacquired and the lock hold 1158 * count restored to what it was when the method was called. 1159 * 1160 * <li>If a thread is {@linkplain Thread#interrupt interrupted} while 1161 * waiting then the wait will terminate, an {@link 1162 * InterruptedException} will be thrown, and the thread's 1163 * interrupted status will be cleared. 1164 * 1165 * <li> Waiting threads are signalled in FIFO order. 1166 * 1167 * <li>The ordering of lock reacquisition for threads returning 1168 * from waiting methods is the same as for threads initially 1169 * acquiring the lock, which is in the default case not specified, 1170 * but for <em>fair</em> locks favors those threads that have been 1171 * waiting the longest. 1172 * 1173 * </ul> 1174 * 1175 * @return the Condition object 1176 */ 1177 public Condition newCondition() { 1178 return sync.newCondition(); 1179 } 1180 1181 /** 1182 * Returns a string identifying this lock, as well as its lock 1183 * state. The state, in brackets includes either the String 1184 * {@code "Unlocked"} or the String {@code "Locked by"} 1185 * followed by the {@linkplain Thread#getName name} of the owning thread. 1186 * 1187 * @return a string identifying this lock, as well as its lock state 1188 */ 1189 public String toString() { 1190 Thread o = sync.getOwner(); 1191 return super.toString() + ((o == null) ? 1192 "[Unlocked]" : 1193 "[Locked by thread " + o.getName() + "]"); 1194 } 1195 1196 /** 1197 * Queries if this write lock is held by the current thread. 1198 * Identical in effect to {@link 1199 * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. 1200 * 1201 * @return {@code true} if the current thread holds this lock and 1202 * {@code false} otherwise 1203 * @since 1.6 1204 */ 1205 public boolean isHeldByCurrentThread() { 1206 return sync.isHeldExclusively(); 1207 } 1208 1209 /** 1210 * Queries the number of holds on this write lock by the current 1211 * thread. A thread has a hold on a lock for each lock action 1212 * that is not matched by an unlock action. Identical in effect 1213 * to {@link ReentrantReadWriteLock#getWriteHoldCount}. 1214 * 1215 * @return the number of holds on this lock by the current thread, 1216 * or zero if this lock is not held by the current thread 1217 * @since 1.6 1218 */ 1219 public int getHoldCount() { 1220 return sync.getWriteHoldCount(); 1221 } 1222 } 1223 1224 // Instrumentation and status 1225 1226 /** 1227 * Returns {@code true} if this lock has fairness set true. 1228 * 1229 * @return {@code true} if this lock has fairness set true 1230 */ 1231 public final boolean isFair() { 1232 return sync instanceof FairSync; 1233 } 1234 1235 /** 1236 * Returns the thread that currently owns the write lock, or 1237 * {@code null} if not owned. When this method is called by a 1238 * thread that is not the owner, the return value reflects a 1239 * best-effort approximation of current lock status. For example, 1240 * the owner may be momentarily {@code null} even if there are 1241 * threads trying to acquire the lock but have not yet done so. 1242 * This method is designed to facilitate construction of 1243 * subclasses that provide more extensive lock monitoring 1244 * facilities. 1245 * 1246 * @return the owner, or {@code null} if not owned 1247 */ 1248 protected Thread getOwner() { 1249 return sync.getOwner(); 1250 } 1251 1252 /** 1253 * Queries the number of read locks held for this lock. This 1254 * method is designed for use in monitoring system state, not for 1255 * synchronization control. 1256 * @return the number of read locks held. 1257 */ 1258 public int getReadLockCount() { 1259 return sync.getReadLockCount(); 1260 } 1261 1262 /** 1263 * Queries if the write lock is held by any thread. This method is 1264 * designed for use in monitoring system state, not for 1265 * synchronization control. 1266 * 1267 * @return {@code true} if any thread holds the write lock and 1268 * {@code false} otherwise 1269 */ 1270 public boolean isWriteLocked() { 1271 return sync.isWriteLocked(); 1272 } 1273 1274 /** 1275 * Queries if the write lock is held by the current thread. 1276 * 1277 * @return {@code true} if the current thread holds the write lock and 1278 * {@code false} otherwise 1279 */ 1280 public boolean isWriteLockedByCurrentThread() { 1281 return sync.isHeldExclusively(); 1282 } 1283 1284 /** 1285 * Queries the number of reentrant write holds on this lock by the 1286 * current thread. A writer thread has a hold on a lock for 1287 * each lock action that is not matched by an unlock action. 1288 * 1289 * @return the number of holds on the write lock by the current thread, 1290 * or zero if the write lock is not held by the current thread 1291 */ 1292 public int getWriteHoldCount() { 1293 return sync.getWriteHoldCount(); 1294 } 1295 1296 /** 1297 * Queries the number of reentrant read holds on this lock by the 1298 * current thread. A reader thread has a hold on a lock for 1299 * each lock action that is not matched by an unlock action. 1300 * 1301 * @return the number of holds on the read lock by the current thread, 1302 * or zero if the read lock is not held by the current thread 1303 * @since 1.6 1304 */ 1305 public int getReadHoldCount() { 1306 return sync.getReadHoldCount(); 1307 } 1308 1309 /** 1310 * Returns a collection containing threads that may be waiting to 1311 * acquire the write lock. Because the actual set of threads may 1312 * change dynamically while constructing this result, the returned 1313 * collection is only a best-effort estimate. The elements of the 1314 * returned collection are in no particular order. This method is 1315 * designed to facilitate construction of subclasses that provide 1316 * more extensive lock monitoring facilities. 1317 * 1318 * @return the collection of threads 1319 */ 1320 protected Collection<Thread> getQueuedWriterThreads() { 1321 return sync.getExclusiveQueuedThreads(); 1322 } 1323 1324 /** 1325 * Returns a collection containing threads that may be waiting to 1326 * acquire the read lock. Because the actual set of threads may 1327 * change dynamically while constructing this result, the returned 1328 * collection is only a best-effort estimate. The elements of the 1329 * returned collection are in no particular order. This method is 1330 * designed to facilitate construction of subclasses that provide 1331 * more extensive lock monitoring facilities. 1332 * 1333 * @return the collection of threads 1334 */ 1335 protected Collection<Thread> getQueuedReaderThreads() { 1336 return sync.getSharedQueuedThreads(); 1337 } 1338 1339 /** 1340 * Queries whether any threads are waiting to acquire the read or 1341 * write lock. Note that because cancellations may occur at any 1342 * time, a {@code true} return does not guarantee that any other 1343 * thread will ever acquire a lock. This method is designed 1344 * primarily for use in monitoring of the system state. 1345 * 1346 * @return {@code true} if there may be other threads waiting to 1347 * acquire the lock 1348 */ 1349 public final boolean hasQueuedThreads() { 1350 return sync.hasQueuedThreads(); 1351 } 1352 1353 /** 1354 * Queries whether the given thread is waiting to acquire either 1355 * the read or write lock. Note that because cancellations may 1356 * occur at any time, a {@code true} return does not guarantee 1357 * that this thread will ever acquire a lock. This method is 1358 * designed primarily for use in monitoring of the system state. 1359 * 1360 * @param thread the thread 1361 * @return {@code true} if the given thread is queued waiting for this lock 1362 * @throws NullPointerException if the thread is null 1363 */ 1364 public final boolean hasQueuedThread(Thread thread) { 1365 return sync.isQueued(thread); 1366 } 1367 1368 /** 1369 * Returns an estimate of the number of threads waiting to acquire 1370 * either the read or write lock. The value is only an estimate 1371 * because the number of threads may change dynamically while this 1372 * method traverses internal data structures. This method is 1373 * designed for use in monitoring of the system state, not for 1374 * synchronization control. 1375 * 1376 * @return the estimated number of threads waiting for this lock 1377 */ 1378 public final int getQueueLength() { 1379 return sync.getQueueLength(); 1380 } 1381 1382 /** 1383 * Returns a collection containing threads that may be waiting to 1384 * acquire either the read or write lock. Because the actual set 1385 * of threads may change dynamically while constructing this 1386 * result, the returned collection is only a best-effort estimate. 1387 * The elements of the returned collection are in no particular 1388 * order. This method is designed to facilitate construction of 1389 * subclasses that provide more extensive monitoring facilities. 1390 * 1391 * @return the collection of threads 1392 */ 1393 protected Collection<Thread> getQueuedThreads() { 1394 return sync.getQueuedThreads(); 1395 } 1396 1397 /** 1398 * Queries whether any threads are waiting on the given condition 1399 * associated with the write lock. Note that because timeouts and 1400 * interrupts may occur at any time, a {@code true} return does 1401 * not guarantee that a future {@code signal} will awaken any 1402 * threads. This method is designed primarily for use in 1403 * monitoring of the system state. 1404 * 1405 * @param condition the condition 1406 * @return {@code true} if there are any waiting threads 1407 * @throws IllegalMonitorStateException if this lock is not held 1408 * @throws IllegalArgumentException if the given condition is 1409 * not associated with this lock 1410 * @throws NullPointerException if the condition is null 1411 */ 1412 public boolean hasWaiters(Condition condition) { 1413 if (condition == null) 1414 throw new NullPointerException(); 1415 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1416 throw new IllegalArgumentException("not owner"); 1417 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); 1418 } 1419 1420 /** 1421 * Returns an estimate of the number of threads waiting on the 1422 * given condition associated with the write lock. Note that because 1423 * timeouts and interrupts may occur at any time, the estimate 1424 * serves only as an upper bound on the actual number of waiters. 1425 * This method is designed for use in monitoring of the system 1426 * state, not for synchronization control. 1427 * 1428 * @param condition the condition 1429 * @return the estimated number of waiting threads 1430 * @throws IllegalMonitorStateException if this lock is not held 1431 * @throws IllegalArgumentException if the given condition is 1432 * not associated with this lock 1433 * @throws NullPointerException if the condition is null 1434 */ 1435 public int getWaitQueueLength(Condition condition) { 1436 if (condition == null) 1437 throw new NullPointerException(); 1438 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1439 throw new IllegalArgumentException("not owner"); 1440 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); 1441 } 1442 1443 /** 1444 * Returns a collection containing those threads that may be 1445 * waiting on the given condition associated with the write lock. 1446 * Because the actual set of threads may change dynamically while 1447 * constructing this result, the returned collection is only a 1448 * best-effort estimate. The elements of the returned collection 1449 * are in no particular order. This method is designed to 1450 * facilitate construction of subclasses that provide more 1451 * extensive condition monitoring facilities. 1452 * 1453 * @param condition the condition 1454 * @return the collection of threads 1455 * @throws IllegalMonitorStateException if this lock is not held 1456 * @throws IllegalArgumentException if the given condition is 1457 * not associated with this lock 1458 * @throws NullPointerException if the condition is null 1459 */ 1460 protected Collection<Thread> getWaitingThreads(Condition condition) { 1461 if (condition == null) 1462 throw new NullPointerException(); 1463 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 1464 throw new IllegalArgumentException("not owner"); 1465 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); 1466 } 1467 1468 /** 1469 * Returns a string identifying this lock, as well as its lock state. 1470 * The state, in brackets, includes the String {@code "Write locks ="} 1471 * followed by the number of reentrantly held write locks, and the 1472 * String {@code "Read locks ="} followed by the number of held 1473 * read locks. 1474 * 1475 * @return a string identifying this lock, as well as its lock state 1476 */ 1477 public String toString() { 1478 int c = sync.getCount(); 1479 int w = Sync.exclusiveCount(c); 1480 int r = Sync.sharedCount(c); 1481 1482 return super.toString() + 1483 "[Write locks = " + w + ", Read locks = " + r + "]"; 1484 } 1485 1486 }
AQS的完整源码
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /* 2 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 */ 24 25 /* 26 * 27 * 28 * 29 * 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.locks; 37 import java.util.*; 38 import java.util.concurrent.*; 39 import java.util.concurrent.atomic.*; 40 import sun.misc.Unsafe; 41 42 /** 43 * Provides a framework for implementing blocking locks and related 44 * synchronizers (semaphores, events, etc) that rely on 45 * first-in-first-out (FIFO) wait queues. This class is designed to 46 * be a useful basis for most kinds of synchronizers that rely on a 47 * single atomic <tt>int</tt> value to represent state. Subclasses 48 * must define the protected methods that change this state, and which 49 * define what that state means in terms of this object being acquired 50 * or released. Given these, the other methods in this class carry 51 * out all queuing and blocking mechanics. Subclasses can maintain 52 * other state fields, but only the atomically updated <tt>int</tt> 53 * value manipulated using methods {@link #getState}, {@link 54 * #setState} and {@link #compareAndSetState} is tracked with respect 55 * to synchronization. 56 * 57 * <p>Subclasses should be defined as non-public internal helper 58 * classes that are used to implement the synchronization properties 59 * of their enclosing class. Class 60 * <tt>AbstractQueuedSynchronizer</tt> does not implement any 61 * synchronization interface. Instead it defines methods such as 62 * {@link #acquireInterruptibly} that can be invoked as 63 * appropriate by concrete locks and related synchronizers to 64 * implement their public methods. 65 * 66 * <p>This class supports either or both a default <em>exclusive</em> 67 * mode and a <em>shared</em> mode. When acquired in exclusive mode, 68 * attempted acquires by other threads cannot succeed. Shared mode 69 * acquires by multiple threads may (but need not) succeed. This class 70 * does not "understand" these differences except in the 71 * mechanical sense that when a shared mode acquire succeeds, the next 72 * waiting thread (if one exists) must also determine whether it can 73 * acquire as well. Threads waiting in the different modes share the 74 * same FIFO queue. Usually, implementation subclasses support only 75 * one of these modes, but both can come into play for example in a 76 * {@link ReadWriteLock}. Subclasses that support only exclusive or 77 * only shared modes need not define the methods supporting the unused mode. 78 * 79 * <p>This class defines a nested {@link ConditionObject} class that 80 * can be used as a {@link Condition} implementation by subclasses 81 * supporting exclusive mode for which method {@link 82 * #isHeldExclusively} reports whether synchronization is exclusively 83 * held with respect to the current thread, method {@link #release} 84 * invoked with the current {@link #getState} value fully releases 85 * this object, and {@link #acquire}, given this saved state value, 86 * eventually restores this object to its previous acquired state. No 87 * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a 88 * condition, so if this constraint cannot be met, do not use it. The 89 * behavior of {@link ConditionObject} depends of course on the 90 * semantics of its synchronizer implementation. 91 * 92 * <p>This class provides inspection, instrumentation, and monitoring 93 * methods for the internal queue, as well as similar methods for 94 * condition objects. These can be exported as desired into classes 95 * using an <tt>AbstractQueuedSynchronizer</tt> for their 96 * synchronization mechanics. 97 * 98 * <p>Serialization of this class stores only the underlying atomic 99 * integer maintaining state, so deserialized objects have empty 100 * thread queues. Typical subclasses requiring serializability will 101 * define a <tt>readObject</tt> method that restores this to a known 102 * initial state upon deserialization. 103 * 104 * <h3>Usage</h3> 105 * 106 * <p>To use this class as the basis of a synchronizer, redefine the 107 * following methods, as applicable, by inspecting and/or modifying 108 * the synchronization state using {@link #getState}, {@link 109 * #setState} and/or {@link #compareAndSetState}: 110 * 111 * <ul> 112 * <li> {@link #tryAcquire} 113 * <li> {@link #tryRelease} 114 * <li> {@link #tryAcquireShared} 115 * <li> {@link #tryReleaseShared} 116 * <li> {@link #isHeldExclusively} 117 *</ul> 118 * 119 * Each of these methods by default throws {@link 120 * UnsupportedOperationException}. Implementations of these methods 121 * must be internally thread-safe, and should in general be short and 122 * not block. Defining these methods is the <em>only</em> supported 123 * means of using this class. All other methods are declared 124 * <tt>final</tt> because they cannot be independently varied. 125 * 126 * <p>You may also find the inherited methods from {@link 127 * AbstractOwnableSynchronizer} useful to keep track of the thread 128 * owning an exclusive synchronizer. You are encouraged to use them 129 * -- this enables monitoring and diagnostic tools to assist users in 130 * determining which threads hold locks. 131 * 132 * <p>Even though this class is based on an internal FIFO queue, it 133 * does not automatically enforce FIFO acquisition policies. The core 134 * of exclusive synchronization takes the form: 135 * 136 * <pre> 137 * Acquire: 138 * while (!tryAcquire(arg)) { 139 * <em>enqueue thread if it is not already queued</em>; 140 * <em>possibly block current thread</em>; 141 * } 142 * 143 * Release: 144 * if (tryRelease(arg)) 145 * <em>unblock the first queued thread</em>; 146 * </pre> 147 * 148 * (Shared mode is similar but may involve cascading signals.) 149 * 150 * <p><a name="barging">Because checks in acquire are invoked before 151 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of 152 * others that are blocked and queued. However, you can, if desired, 153 * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to 154 * disable barging by internally invoking one or more of the inspection 155 * methods, thereby providing a <em>fair</em> FIFO acquisition order. 156 * In particular, most fair synchronizers can define <tt>tryAcquire</tt> 157 * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method 158 * specifically designed to be used by fair synchronizers) returns 159 * <tt>true</tt>. Other variations are possible. 160 * 161 * <p>Throughput and scalability are generally highest for the 162 * default barging (also known as <em>greedy</em>, 163 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy. 164 * While this is not guaranteed to be fair or starvation-free, earlier 165 * queued threads are allowed to recontend before later queued 166 * threads, and each recontention has an unbiased chance to succeed 167 * against incoming threads. Also, while acquires do not 168 * "spin" in the usual sense, they may perform multiple 169 * invocations of <tt>tryAcquire</tt> interspersed with other 170 * computations before blocking. This gives most of the benefits of 171 * spins when exclusive synchronization is only briefly held, without 172 * most of the liabilities when it isn't. If so desired, you can 173 * augment this by preceding calls to acquire methods with 174 * "fast-path" checks, possibly prechecking {@link #hasContended} 175 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer 176 * is likely not to be contended. 177 * 178 * <p>This class provides an efficient and scalable basis for 179 * synchronization in part by specializing its range of use to 180 * synchronizers that can rely on <tt>int</tt> state, acquire, and 181 * release parameters, and an internal FIFO wait queue. When this does 182 * not suffice, you can build synchronizers from a lower level using 183 * {@link java.util.concurrent.atomic atomic} classes, your own custom 184 * {@link java.util.Queue} classes, and {@link LockSupport} blocking 185 * support. 186 * 187 * <h3>Usage Examples</h3> 188 * 189 * <p>Here is a non-reentrant mutual exclusion lock class that uses 190 * the value zero to represent the unlocked state, and one to 191 * represent the locked state. While a non-reentrant lock 192 * does not strictly require recording of the current owner 193 * thread, this class does so anyway to make usage easier to monitor. 194 * It also supports conditions and exposes 195 * one of the instrumentation methods: 196 * 197 * <pre> 198 * class Mutex implements Lock, java.io.Serializable { 199 * 200 * // Our internal helper class 201 * private static class Sync extends AbstractQueuedSynchronizer { 202 * // Report whether in locked state 203 * protected boolean isHeldExclusively() { 204 * return getState() == 1; 205 * } 206 * 207 * // Acquire the lock if state is zero 208 * public boolean tryAcquire(int acquires) { 209 * assert acquires == 1; // Otherwise unused 210 * if (compareAndSetState(0, 1)) { 211 * setExclusiveOwnerThread(Thread.currentThread()); 212 * return true; 213 * } 214 * return false; 215 * } 216 * 217 * // Release the lock by setting state to zero 218 * protected boolean tryRelease(int releases) { 219 * assert releases == 1; // Otherwise unused 220 * if (getState() == 0) throw new IllegalMonitorStateException(); 221 * setExclusiveOwnerThread(null); 222 * setState(0); 223 * return true; 224 * } 225 * 226 * // Provide a Condition 227 * Condition newCondition() { return new ConditionObject(); } 228 * 229 * // Deserialize properly 230 * private void readObject(ObjectInputStream s) 231 * throws IOException, ClassNotFoundException { 232 * s.defaultReadObject(); 233 * setState(0); // reset to unlocked state 234 * } 235 * } 236 * 237 * // The sync object does all the hard work. We just forward to it. 238 * private final Sync sync = new Sync(); 239 * 240 * public void lock() { sync.acquire(1); } 241 * public boolean tryLock() { return sync.tryAcquire(1); } 242 * public void unlock() { sync.release(1); } 243 * public Condition newCondition() { return sync.newCondition(); } 244 * public boolean isLocked() { return sync.isHeldExclusively(); } 245 * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } 246 * public void lockInterruptibly() throws InterruptedException { 247 * sync.acquireInterruptibly(1); 248 * } 249 * public boolean tryLock(long timeout, TimeUnit unit) 250 * throws InterruptedException { 251 * return sync.tryAcquireNanos(1, unit.toNanos(timeout)); 252 * } 253 * } 254 * </pre> 255 * 256 * <p>Here is a latch class that is like a {@link CountDownLatch} 257 * except that it only requires a single <tt>signal</tt> to 258 * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt> 259 * acquire and release methods. 260 * 261 * <pre> 262 * class BooleanLatch { 263 * 264 * private static class Sync extends AbstractQueuedSynchronizer { 265 * boolean isSignalled() { return getState() != 0; } 266 * 267 * protected int tryAcquireShared(int ignore) { 268 * return isSignalled() ? 1 : -1; 269 * } 270 * 271 * protected boolean tryReleaseShared(int ignore) { 272 * setState(1); 273 * return true; 274 * } 275 * } 276 * 277 * private final Sync sync = new Sync(); 278 * public boolean isSignalled() { return sync.isSignalled(); } 279 * public void signal() { sync.releaseShared(1); } 280 * public void await() throws InterruptedException { 281 * sync.acquireSharedInterruptibly(1); 282 * } 283 * } 284 * </pre> 285 * 286 * @since 1.5 287 * @author Doug Lea 288 */ 289 public abstract class AbstractQueuedSynchronizer 290 extends AbstractOwnableSynchronizer 291 implements java.io.Serializable { 292 293 private static final long serialVersionUID = 7373984972572414691L; 294 295 /** 296 * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance 297 * with initial synchronization state of zero. 298 */ 299 protected AbstractQueuedSynchronizer() { } 300 301 /** 302 * Wait queue node class. 303 * 304 * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and 305 * Hagersten) lock queue. CLH locks are normally used for 306 * spinlocks. We instead use them for blocking synchronizers, but 307 * use the same basic tactic of holding some of the control 308 * information about a thread in the predecessor of its node. A 309 * "status" field in each node keeps track of whether a thread 310 * should block. A node is signalled when its predecessor 311 * releases. Each node of the queue otherwise serves as a 312 * specific-notification-style monitor holding a single waiting 313 * thread. The status field does NOT control whether threads are 314 * granted locks etc though. A thread may try to acquire if it is 315 * first in the queue. But being first does not guarantee success; 316 * it only gives the right to contend. So the currently released 317 * contender thread may need to rewait. 318 * 319 * <p>To enqueue into a CLH lock, you atomically splice it in as new 320 * tail. To dequeue, you just set the head field. 321 * <pre> 322 * +------+ prev +-----+ +-----+ 323 * head | | <---- | | <---- | | tail 324 * +------+ +-----+ +-----+ 325 * </pre> 326 * 327 * <p>Insertion into a CLH queue requires only a single atomic 328 * operation on "tail", so there is a simple atomic point of 329 * demarcation from unqueued to queued. Similarly, dequeing 330 * involves only updating the "head". However, it takes a bit 331 * more work for nodes to determine who their successors are, 332 * in part to deal with possible cancellation due to timeouts 333 * and interrupts. 334 * 335 * <p>The "prev" links (not used in original CLH locks), are mainly 336 * needed to handle cancellation. If a node is cancelled, its 337 * successor is (normally) relinked to a non-cancelled 338 * predecessor. For explanation of similar mechanics in the case 339 * of spin locks, see the papers by Scott and Scherer at 340 * http://www.cs.rochester.edu/u/scott/synchronization/ 341 * 342 * <p>We also use "next" links to implement blocking mechanics. 343 * The thread id for each node is kept in its own node, so a 344 * predecessor signals the next node to wake up by traversing 345 * next link to determine which thread it is. Determination of 346 * successor must avoid races with newly queued nodes to set 347 * the "next" fields of their predecessors. This is solved 348 * when necessary by checking backwards from the atomically 349 * updated "tail" when a node's successor appears to be null. 350 * (Or, said differently, the next-links are an optimization 351 * so that we don't usually need a backward scan.) 352 * 353 * <p>Cancellation introduces some conservatism to the basic 354 * algorithms. Since we must poll for cancellation of other 355 * nodes, we can miss noticing whether a cancelled node is 356 * ahead or behind us. This is dealt with by always unparking 357 * successors upon cancellation, allowing them to stabilize on 358 * a new predecessor, unless we can identify an uncancelled 359 * predecessor who will carry this responsibility. 360 * 361 * <p>CLH queues need a dummy header node to get started. But 362 * we don't create them on construction, because it would be wasted 363 * effort if there is never contention. Instead, the node 364 * is constructed and head and tail pointers are set upon first 365 * contention. 366 * 367 * <p>Threads waiting on Conditions use the same nodes, but 368 * use an additional link. Conditions only need to link nodes 369 * in simple (non-concurrent) linked queues because they are 370 * only accessed when exclusively held. Upon await, a node is 371 * inserted into a condition queue. Upon signal, the node is 372 * transferred to the main queue. A special value of status 373 * field is used to mark which queue a node is on. 374 * 375 * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill 376 * Scherer and Michael Scott, along with members of JSR-166 377 * expert group, for helpful ideas, discussions, and critiques 378 * on the design of this class. 379 */ 380 static final class Node { 381 /** Marker to indicate a node is waiting in shared mode */ 382 static final Node SHARED = new Node(); 383 /** Marker to indicate a node is waiting in exclusive mode */ 384 static final Node EXCLUSIVE = null; 385 386 /** waitStatus value to indicate thread has cancelled */ 387 static final int CANCELLED = 1; 388 /** waitStatus value to indicate successor's thread needs unparking */ 389 static final int SIGNAL = -1; 390 /** waitStatus value to indicate thread is waiting on condition */ 391 static final int CONDITION = -2; 392 /** 393 * waitStatus value to indicate the next acquireShared should 394 * unconditionally propagate 395 */ 396 static final int PROPAGATE = -3; 397 398 /** 399 * Status field, taking on only the values: 400 * SIGNAL: The successor of this node is (or will soon be) 401 * blocked (via park), so the current node must 402 * unpark its successor when it releases or 403 * cancels. To avoid races, acquire methods must 404 * first indicate they need a signal, 405 * then retry the atomic acquire, and then, 406 * on failure, block. 407 * CANCELLED: This node is cancelled due to timeout or interrupt. 408 * Nodes never leave this state. In particular, 409 * a thread with cancelled node never again blocks. 410 * CONDITION: This node is currently on a condition queue. 411 * It will not be used as a sync queue node 412 * until transferred, at which time the status 413 * will be set to 0. (Use of this value here has 414 * nothing to do with the other uses of the 415 * field, but simplifies mechanics.) 416 * PROPAGATE: A releaseShared should be propagated to other 417 * nodes. This is set (for head node only) in 418 * doReleaseShared to ensure propagation 419 * continues, even if other operations have 420 * since intervened. 421 * 0: None of the above 422 * 423 * The values are arranged numerically to simplify use. 424 * Non-negative values mean that a node doesn't need to 425 * signal. So, most code doesn't need to check for particular 426 * values, just for sign. 427 * 428 * The field is initialized to 0 for normal sync nodes, and 429 * CONDITION for condition nodes. It is modified using CAS 430 * (or when possible, unconditional volatile writes). 431 */ 432 volatile int waitStatus; 433 434 /** 435 * Link to predecessor node that current node/thread relies on 436 * for checking waitStatus. Assigned during enqueing, and nulled 437 * out (for sake of GC) only upon dequeuing. Also, upon 438 * cancellation of a predecessor, we short-circuit while 439 * finding a non-cancelled one, which will always exist 440 * because the head node is never cancelled: A node becomes 441 * head only as a result of successful acquire. A 442 * cancelled thread never succeeds in acquiring, and a thread only 443 * cancels itself, not any other node. 444 */ 445 volatile Node prev; 446 447 /** 448 * Link to the successor node that the current node/thread 449 * unparks upon release. Assigned during enqueuing, adjusted 450 * when bypassing cancelled predecessors, and nulled out (for 451 * sake of GC) when dequeued. The enq operation does not 452 * assign next field of a predecessor until after attachment, 453 * so seeing a null next field does not necessarily mean that 454 * node is at end of queue. However, if a next field appears 455 * to be null, we can scan prev's from the tail to 456 * double-check. The next field of cancelled nodes is set to 457 * point to the node itself instead of null, to make life 458 * easier for isOnSyncQueue. 459 */ 460 volatile Node next; 461 462 /** 463 * The thread that enqueued this node. Initialized on 464 * construction and nulled out after use. 465 */ 466 volatile Thread thread; 467 468 /** 469 * Link to next node waiting on condition, or the special 470 * value SHARED. Because condition queues are accessed only 471 * when holding in exclusive mode, we just need a simple 472 * linked queue to hold nodes while they are waiting on 473 * conditions. They are then transferred to the queue to 474 * re-acquire. And because conditions can only be exclusive, 475 * we save a field by using special value to indicate shared 476 * mode. 477 */ 478 Node nextWaiter; 479 480 /** 481 * Returns true if node is waiting in shared mode 482 */ 483 final boolean isShared() { 484 return nextWaiter == SHARED; 485 } 486 487 /** 488 * Returns previous node, or throws NullPointerException if null. 489 * Use when predecessor cannot be null. The null check could 490 * be elided, but is present to help the VM. 491 * 492 * @return the predecessor of this node 493 */ 494 final Node predecessor() throws NullPointerException { 495 Node p = prev; 496 if (p == null) 497 throw new NullPointerException(); 498 else 499 return p; 500 } 501 502 Node() { // Used to establish initial head or SHARED marker 503 } 504 505 Node(Thread thread, Node mode) { // Used by addWaiter 506 this.nextWaiter = mode; 507 this.thread = thread; 508 } 509 510 Node(Thread thread, int waitStatus) { // Used by Condition 511 this.waitStatus = waitStatus; 512 this.thread = thread; 513 } 514 } 515 516 /** 517 * Head of the wait queue, lazily initialized. Except for 518 * initialization, it is modified only via method setHead. Note: 519 * If head exists, its waitStatus is guaranteed not to be 520 * CANCELLED. 521 */ 522 private transient volatile Node head; 523 524 /** 525 * Tail of the wait queue, lazily initialized. Modified only via 526 * method enq to add new wait node. 527 */ 528 private transient volatile Node tail; 529 530 /** 531 * The synchronization state. 532 */ 533 private volatile int state; 534 535 /** 536 * Returns the current value of synchronization state. 537 * This operation has memory semantics of a <tt>volatile</tt> read. 538 * @return current state value 539 */ 540 protected final int getState() { 541 return state; 542 } 543 544 /** 545 * Sets the value of synchronization state. 546 * This operation has memory semantics of a <tt>volatile</tt> write. 547 * @param newState the new state value 548 */ 549 protected final void setState(int newState) { 550 state = newState; 551 } 552 553 /** 554 * Atomically sets synchronization state to the given updated 555 * value if the current state value equals the expected value. 556 * This operation has memory semantics of a <tt>volatile</tt> read 557 * and write. 558 * 559 * @param expect the expected value 560 * @param update the new value 561 * @return true if successful. False return indicates that the actual 562 * value was not equal to the expected value. 563 */ 564 protected final boolean compareAndSetState(int expect, int update) { 565 // See below for intrinsics setup to support this 566 return unsafe.compareAndSwapInt(this, stateOffset, expect, update); 567 } 568 569 // Queuing utilities 570 571 /** 572 * The number of nanoseconds for which it is faster to spin 573 * rather than to use timed park. A rough estimate suffices 574 * to improve responsiveness with very short timeouts. 575 */ 576 static final long spinForTimeoutThreshold = 1000L; 577 578 /** 579 * Inserts node into queue, initializing if necessary. See picture above. 580 * @param node the node to insert 581 * @return node's predecessor 582 */ 583 private Node enq(final Node node) { 584 for (;;) { 585 Node t = tail; 586 if (t == null) { // Must initialize 587 if (compareAndSetHead(new Node())) 588 tail = head; 589 } else { 590 node.prev = t; 591 if (compareAndSetTail(t, node)) { 592 t.next = node; 593 return t; 594 } 595 } 596 } 597 } 598 599 /** 600 * Creates and enqueues node for current thread and given mode. 601 * 602 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 603 * @return the new node 604 */ 605 private Node addWaiter(Node mode) { 606 Node node = new Node(Thread.currentThread(), mode); 607 // Try the fast path of enq; backup to full enq on failure 608 Node pred = tail; 609 if (pred != null) { 610 node.prev = pred; 611 if (compareAndSetTail(pred, node)) { 612 pred.next = node; 613 return node; 614 } 615 } 616 enq(node); 617 return node; 618 } 619 620 /** 621 * Sets head of queue to be node, thus dequeuing. Called only by 622 * acquire methods. Also nulls out unused fields for sake of GC 623 * and to suppress unnecessary signals and traversals. 624 * 625 * @param node the node 626 */ 627 private void setHead(Node node) { 628 head = node; 629 node.thread = null; 630 node.prev = null; 631 } 632 633 /** 634 * Wakes up node's successor, if one exists. 635 * 636 * @param node the node 637 */ 638 private void unparkSuccessor(Node node) { 639 /* 640 * If status is negative (i.e., possibly needing signal) try 641 * to clear in anticipation of signalling. It is OK if this 642 * fails or if status is changed by waiting thread. 643 */ 644 int ws = node.waitStatus; 645 if (ws < 0) 646 compareAndSetWaitStatus(node, ws, 0); 647 648 /* 649 * Thread to unpark is held in successor, which is normally 650 * just the next node. But if cancelled or apparently null, 651 * traverse backwards from tail to find the actual 652 * non-cancelled successor. 653 */ 654 Node s = node.next; 655 if (s == null || s.waitStatus > 0) { 656 s = null; 657 for (Node t = tail; t != null && t != node; t = t.prev) 658 if (t.waitStatus <= 0) 659 s = t; 660 } 661 if (s != null) 662 LockSupport.unpark(s.thread); 663 } 664 665 /** 666 * Release action for shared mode -- signal successor and ensure 667 * propagation. (Note: For exclusive mode, release just amounts 668 * to calling unparkSuccessor of head if it needs signal.) 669 */ 670 private void doReleaseShared() { 671 /* 672 * Ensure that a release propagates, even if there are other 673 * in-progress acquires/releases. This proceeds in the usual 674 * way of trying to unparkSuccessor of head if it needs 675 * signal. But if it does not, status is set to PROPAGATE to 676 * ensure that upon release, propagation continues. 677 * Additionally, we must loop in case a new node is added 678 * while we are doing this. Also, unlike other uses of 679 * unparkSuccessor, we need to know if CAS to reset status 680 * fails, if so rechecking. 681 */ 682 for (;;) { 683 Node h = head; 684 if (h != null && h != tail) { 685 int ws = h.waitStatus; 686 if (ws == Node.SIGNAL) { 687 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) 688 continue; // loop to recheck cases 689 unparkSuccessor(h); 690 } 691 else if (ws == 0 && 692 !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) 693 continue; // loop on failed CAS 694 } 695 if (h == head) // loop if head changed 696 break; 697 } 698 } 699 700 /** 701 * Sets head of queue, and checks if successor may be waiting 702 * in shared mode, if so propagating if either propagate > 0 or 703 * PROPAGATE status was set. 704 * 705 * @param node the node 706 * @param propagate the return value from a tryAcquireShared 707 */ 708 private void setHeadAndPropagate(Node node, int propagate) { 709 Node h = head; // Record old head for check below 710 setHead(node); 711 /* 712 * Try to signal next queued node if: 713 * Propagation was indicated by caller, 714 * or was recorded (as h.waitStatus) by a previous operation 715 * (note: this uses sign-check of waitStatus because 716 * PROPAGATE status may transition to SIGNAL.) 717 * and 718 * The next node is waiting in shared mode, 719 * or we don't know, because it appears null 720 * 721 * The conservatism in both of these checks may cause 722 * unnecessary wake-ups, but only when there are multiple 723 * racing acquires/releases, so most need signals now or soon 724 * anyway. 725 */ 726 if (propagate > 0 || h == null || h.waitStatus < 0) { 727 Node s = node.next; 728 if (s == null || s.isShared()) 729 doReleaseShared(); 730 } 731 } 732 733 // Utilities for various versions of acquire 734 735 /** 736 * Cancels an ongoing attempt to acquire. 737 * 738 * @param node the node 739 */ 740 private void cancelAcquire(Node node) { 741 // Ignore if node doesn't exist 742 if (node == null) 743 return; 744 745 node.thread = null; 746 747 // Skip cancelled predecessors 748 Node pred = node.prev; 749 while (pred.waitStatus > 0) 750 node.prev = pred = pred.prev; 751 752 // predNext is the apparent node to unsplice. CASes below will 753 // fail if not, in which case, we lost race vs another cancel 754 // or signal, so no further action is necessary. 755 Node predNext = pred.next; 756 757 // Can use unconditional write instead of CAS here. 758 // After this atomic step, other Nodes can skip past us. 759 // Before, we are free of interference from other threads. 760 node.waitStatus = Node.CANCELLED; 761 762 // If we are the tail, remove ourselves. 763 if (node == tail && compareAndSetTail(node, pred)) { 764 compareAndSetNext(pred, predNext, null); 765 } else { 766 // If successor needs signal, try to set pred's next-link 767 // so it will get one. Otherwise wake it up to propagate. 768 int ws; 769 if (pred != head && 770 ((ws = pred.waitStatus) == Node.SIGNAL || 771 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && 772 pred.thread != null) { 773 Node next = node.next; 774 if (next != null && next.waitStatus <= 0) 775 compareAndSetNext(pred, predNext, next); 776 } else { 777 unparkSuccessor(node); 778 } 779 780 node.next = node; // help GC 781 } 782 } 783 784 /** 785 * Checks and updates status for a node that failed to acquire. 786 * Returns true if thread should block. This is the main signal 787 * control in all acquire loops. Requires that pred == node.prev 788 * 789 * @param pred node's predecessor holding status 790 * @param node the node 791 * @return {@code true} if thread should block 792 */ 793 private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { 794 int ws = pred.waitStatus; 795 if (ws == Node.SIGNAL) 796 /* 797 * This node has already set status asking a release 798 * to signal it, so it can safely park. 799 */ 800 return true; 801 if (ws > 0) { 802 /* 803 * Predecessor was cancelled. Skip over predecessors and 804 * indicate retry. 805 */ 806 do { 807 node.prev = pred = pred.prev; 808 } while (pred.waitStatus > 0); 809 pred.next = node; 810 } else { 811 /* 812 * waitStatus must be 0 or PROPAGATE. Indicate that we 813 * need a signal, but don't park yet. Caller will need to 814 * retry to make sure it cannot acquire before parking. 815 */ 816 compareAndSetWaitStatus(pred, ws, Node.SIGNAL); 817 } 818 return false; 819 } 820 821 /** 822 * Convenience method to interrupt current thread. 823 */ 824 private static void selfInterrupt() { 825 Thread.currentThread().interrupt(); 826 } 827 828 /** 829 * Convenience method to park and then check if interrupted 830 * 831 * @return {@code true} if interrupted 832 */ 833 private final boolean parkAndCheckInterrupt() { 834 LockSupport.park(this); 835 return Thread.interrupted(); 836 } 837 838 /* 839 * Various flavors of acquire, varying in exclusive/shared and 840 * control modes. Each is mostly the same, but annoyingly 841 * different. Only a little bit of factoring is possible due to 842 * interactions of exception mechanics (including ensuring that we 843 * cancel if tryAcquire throws exception) and other control, at 844 * least not without hurting performance too much. 845 */ 846 847 /** 848 * Acquires in exclusive uninterruptible mode for thread already in 849 * queue. Used by condition wait methods as well as acquire. 850 * 851 * @param node the node 852 * @param arg the acquire argument 853 * @return {@code true} if interrupted while waiting 854 */ 855 final boolean acquireQueued(final Node node, int arg) { 856 boolean failed = true; 857 try { 858 boolean interrupted = false; 859 for (;;) { 860 final Node p = node.predecessor(); 861 if (p == head && tryAcquire(arg)) { 862 setHead(node); 863 p.next = null; // help GC 864 failed = false; 865 return interrupted; 866 } 867 if (shouldParkAfterFailedAcquire(p, node) && 868 parkAndCheckInterrupt()) 869 interrupted = true; 870 } 871 } finally { 872 if (failed) 873 cancelAcquire(node); 874 } 875 } 876 877 /** 878 * Acquires in exclusive interruptible mode. 879 * @param arg the acquire argument 880 */ 881 private void doAcquireInterruptibly(int arg) 882 throws InterruptedException { 883 final Node node = addWaiter(Node.EXCLUSIVE); 884 boolean failed = true; 885 try { 886 for (;;) { 887 final Node p = node.predecessor(); 888 if (p == head && tryAcquire(arg)) { 889 setHead(node); 890 p.next = null; // help GC 891 failed = false; 892 return; 893 } 894 if (shouldParkAfterFailedAcquire(p, node) && 895 parkAndCheckInterrupt()) 896 throw new InterruptedException(); 897 } 898 } finally { 899 if (failed) 900 cancelAcquire(node); 901 } 902 } 903 904 /** 905 * Acquires in exclusive timed mode. 906 * 907 * @param arg the acquire argument 908 * @param nanosTimeout max wait time 909 * @return {@code true} if acquired 910 */ 911 private boolean doAcquireNanos(int arg, long nanosTimeout) 912 throws InterruptedException { 913 long lastTime = System.nanoTime(); 914 final Node node = addWaiter(Node.EXCLUSIVE); 915 boolean failed = true; 916 try { 917 for (;;) { 918 final Node p = node.predecessor(); 919 if (p == head && tryAcquire(arg)) { 920 setHead(node); 921 p.next = null; // help GC 922 failed = false; 923 return true; 924 } 925 if (nanosTimeout <= 0) 926 return false; 927 if (shouldParkAfterFailedAcquire(p, node) && 928 nanosTimeout > spinForTimeoutThreshold) 929 LockSupport.parkNanos(this, nanosTimeout); 930 long now = System.nanoTime(); 931 nanosTimeout -= now - lastTime; 932 lastTime = now; 933 if (Thread.interrupted()) 934 throw new InterruptedException(); 935 } 936 } finally { 937 if (failed) 938 cancelAcquire(node); 939 } 940 } 941 942 /** 943 * Acquires in shared uninterruptible mode. 944 * @param arg the acquire argument 945 */ 946 private void doAcquireShared(int arg) { 947 final Node node = addWaiter(Node.SHARED); 948 boolean failed = true; 949 try { 950 boolean interrupted = false; 951 for (;;) { 952 final Node p = node.predecessor(); 953 if (p == head) { 954 int r = tryAcquireShared(arg); 955 if (r >= 0) { 956 setHeadAndPropagate(node, r); 957 p.next = null; // help GC 958 if (interrupted) 959 selfInterrupt(); 960 failed = false; 961 return; 962 } 963 } 964 if (shouldParkAfterFailedAcquire(p, node) && 965 parkAndCheckInterrupt()) 966 interrupted = true; 967 } 968 } finally { 969 if (failed) 970 cancelAcquire(node); 971 } 972 } 973 974 /** 975 * Acquires in shared interruptible mode. 976 * @param arg the acquire argument 977 */ 978 private void doAcquireSharedInterruptibly(int arg) 979 throws InterruptedException { 980 final Node node = addWaiter(Node.SHARED); 981 boolean failed = true; 982 try { 983 for (;;) { 984 final Node p = node.predecessor(); 985 if (p == head) { 986 int r = tryAcquireShared(arg); 987 if (r >= 0) { 988 setHeadAndPropagate(node, r); 989 p.next = null; // help GC 990 failed = false; 991 return; 992 } 993 } 994 if (shouldParkAfterFailedAcquire(p, node) && 995 parkAndCheckInterrupt()) 996 throw new InterruptedException(); 997 } 998 } finally { 999 if (failed) 1000 cancelAcquire(node); 1001 } 1002 } 1003 1004 /** 1005 * Acquires in shared timed mode. 1006 * 1007 * @param arg the acquire argument 1008 * @param nanosTimeout max wait time 1009 * @return {@code true} if acquired 1010 */ 1011 private boolean doAcquireSharedNanos(int arg, long nanosTimeout) 1012 throws InterruptedException { 1013 1014 long lastTime = System.nanoTime(); 1015 final Node node = addWaiter(Node.SHARED); 1016 boolean failed = true; 1017 try { 1018 for (;;) { 1019 final Node p = node.predecessor(); 1020 if (p == head) { 1021 int r = tryAcquireShared(arg); 1022 if (r >= 0) { 1023 setHeadAndPropagate(node, r); 1024 p.next = null; // help GC 1025 failed = false; 1026 return true; 1027 } 1028 } 1029 if (nanosTimeout <= 0) 1030 return false; 1031 if (shouldParkAfterFailedAcquire(p, node) && 1032 nanosTimeout > spinForTimeoutThreshold) 1033 LockSupport.parkNanos(this, nanosTimeout); 1034 long now = System.nanoTime(); 1035 nanosTimeout -= now - lastTime; 1036 lastTime = now; 1037 if (Thread.interrupted()) 1038 throw new InterruptedException(); 1039 } 1040 } finally { 1041 if (failed) 1042 cancelAcquire(node); 1043 } 1044 } 1045 1046 // Main exported methods 1047 1048 /** 1049 * Attempts to acquire in exclusive mode. This method should query 1050 * if the state of the object permits it to be acquired in the 1051 * exclusive mode, and if so to acquire it. 1052 * 1053 * <p>This method is always invoked by the thread performing 1054 * acquire. If this method reports failure, the acquire method 1055 * may queue the thread, if it is not already queued, until it is 1056 * signalled by a release from some other thread. This can be used 1057 * to implement method {@link Lock#tryLock()}. 1058 * 1059 * <p>The default 1060 * implementation throws {@link UnsupportedOperationException}. 1061 * 1062 * @param arg the acquire argument. This value is always the one 1063 * passed to an acquire method, or is the value saved on entry 1064 * to a condition wait. The value is otherwise uninterpreted 1065 * and can represent anything you like. 1066 * @return {@code true} if successful. Upon success, this object has 1067 * been acquired. 1068 * @throws IllegalMonitorStateException if acquiring would place this 1069 * synchronizer in an illegal state. This exception must be 1070 * thrown in a consistent fashion for synchronization to work 1071 * correctly. 1072 * @throws UnsupportedOperationException if exclusive mode is not supported 1073 */ 1074 protected boolean tryAcquire(int arg) { 1075 throw new UnsupportedOperationException(); 1076 } 1077 1078 /** 1079 * Attempts to set the state to reflect a release in exclusive 1080 * mode. 1081 * 1082 * <p>This method is always invoked by the thread performing release. 1083 * 1084 * <p>The default implementation throws 1085 * {@link UnsupportedOperationException}. 1086 * 1087 * @param arg the release argument. This value is always the one 1088 * passed to a release method, or the current state value upon 1089 * entry to a condition wait. The value is otherwise 1090 * uninterpreted and can represent anything you like. 1091 * @return {@code true} if this object is now in a fully released 1092 * state, so that any waiting threads may attempt to acquire; 1093 * and {@code false} otherwise. 1094 * @throws IllegalMonitorStateException if releasing would place this 1095 * synchronizer in an illegal state. This exception must be 1096 * thrown in a consistent fashion for synchronization to work 1097 * correctly. 1098 * @throws UnsupportedOperationException if exclusive mode is not supported 1099 */ 1100 protected boolean tryRelease(int arg) { 1101 throw new UnsupportedOperationException(); 1102 } 1103 1104 /** 1105 * Attempts to acquire in shared mode. This method should query if 1106 * the state of the object permits it to be acquired in the shared 1107 * mode, and if so to acquire it. 1108 * 1109 * <p>This method is always invoked by the thread performing 1110 * acquire. If this method reports failure, the acquire method 1111 * may queue the thread, if it is not already queued, until it is 1112 * signalled by a release from some other thread. 1113 * 1114 * <p>The default implementation throws {@link 1115 * UnsupportedOperationException}. 1116 * 1117 * @param arg the acquire argument. This value is always the one 1118 * passed to an acquire method, or is the value saved on entry 1119 * to a condition wait. The value is otherwise uninterpreted 1120 * and can represent anything you like. 1121 * @return a negative value on failure; zero if acquisition in shared 1122 * mode succeeded but no subsequent shared-mode acquire can 1123 * succeed; and a positive value if acquisition in shared 1124 * mode succeeded and subsequent shared-mode acquires might 1125 * also succeed, in which case a subsequent waiting thread 1126 * must check availability. (Support for three different 1127 * return values enables this method to be used in contexts 1128 * where acquires only sometimes act exclusively.) Upon 1129 * success, this object has been acquired. 1130 * @throws IllegalMonitorStateException if acquiring would place this 1131 * synchronizer in an illegal state. This exception must be 1132 * thrown in a consistent fashion for synchronization to work 1133 * correctly. 1134 * @throws UnsupportedOperationException if shared mode is not supported 1135 */ 1136 protected int tryAcquireShared(int arg) { 1137 throw new UnsupportedOperationException(); 1138 } 1139 1140 /** 1141 * Attempts to set the state to reflect a release in shared mode. 1142 * 1143 * <p>This method is always invoked by the thread performing release. 1144 * 1145 * <p>The default implementation throws 1146 * {@link UnsupportedOperationException}. 1147 * 1148 * @param arg the release argument. This value is always the one 1149 * passed to a release method, or the current state value upon 1150 * entry to a condition wait. The value is otherwise 1151 * uninterpreted and can represent anything you like. 1152 * @return {@code true} if this release of shared mode may permit a 1153 * waiting acquire (shared or exclusive) to succeed; and 1154 * {@code false} otherwise 1155 * @throws IllegalMonitorStateException if releasing would place this 1156 * synchronizer in an illegal state. This exception must be 1157 * thrown in a consistent fashion for synchronization to work 1158 * correctly. 1159 * @throws UnsupportedOperationException if shared mode is not supported 1160 */ 1161 protected boolean tryReleaseShared(int arg) { 1162 throw new UnsupportedOperationException(); 1163 } 1164 1165 /** 1166 * Returns {@code true} if synchronization is held exclusively with 1167 * respect to the current (calling) thread. This method is invoked 1168 * upon each call to a non-waiting {@link ConditionObject} method. 1169 * (Waiting methods instead invoke {@link #release}.) 1170 * 1171 * <p>The default implementation throws {@link 1172 * UnsupportedOperationException}. This method is invoked 1173 * internally only within {@link ConditionObject} methods, so need 1174 * not be defined if conditions are not used. 1175 * 1176 * @return {@code true} if synchronization is held exclusively; 1177 * {@code false} otherwise 1178 * @throws UnsupportedOperationException if conditions are not supported 1179 */ 1180 protected boolean isHeldExclusively() { 1181 throw new UnsupportedOperationException(); 1182 } 1183 1184 /** 1185 * Acquires in exclusive mode, ignoring interrupts. Implemented 1186 * by invoking at least once {@link #tryAcquire}, 1187 * returning on success. Otherwise the thread is queued, possibly 1188 * repeatedly blocking and unblocking, invoking {@link 1189 * #tryAcquire} until success. This method can be used 1190 * to implement method {@link Lock#lock}. 1191 * 1192 * @param arg the acquire argument. This value is conveyed to 1193 * {@link #tryAcquire} but is otherwise uninterpreted and 1194 * can represent anything you like. 1195 */ 1196 public final void acquire(int arg) { 1197 if (!tryAcquire(arg) && 1198 acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) 1199 selfInterrupt(); 1200 } 1201 1202 /** 1203 * Acquires in exclusive mode, aborting if interrupted. 1204 * Implemented by first checking interrupt status, then invoking 1205 * at least once {@link #tryAcquire}, returning on 1206 * success. Otherwise the thread is queued, possibly repeatedly 1207 * blocking and unblocking, invoking {@link #tryAcquire} 1208 * until success or the thread is interrupted. This method can be 1209 * used to implement method {@link Lock#lockInterruptibly}. 1210 * 1211 * @param arg the acquire argument. This value is conveyed to 1212 * {@link #tryAcquire} but is otherwise uninterpreted and 1213 * can represent anything you like. 1214 * @throws InterruptedException if the current thread is interrupted 1215 */ 1216 public final void acquireInterruptibly(int arg) 1217 throws InterruptedException { 1218 if (Thread.interrupted()) 1219 throw new InterruptedException(); 1220 if (!tryAcquire(arg)) 1221 doAcquireInterruptibly(arg); 1222 } 1223 1224 /** 1225 * Attempts to acquire in exclusive mode, aborting if interrupted, 1226 * and failing if the given timeout elapses. Implemented by first 1227 * checking interrupt status, then invoking at least once {@link 1228 * #tryAcquire}, returning on success. Otherwise, the thread is 1229 * queued, possibly repeatedly blocking and unblocking, invoking 1230 * {@link #tryAcquire} until success or the thread is interrupted 1231 * or the timeout elapses. This method can be used to implement 1232 * method {@link Lock#tryLock(long, TimeUnit)}. 1233 * 1234 * @param arg the acquire argument. This value is conveyed to 1235 * {@link #tryAcquire} but is otherwise uninterpreted and 1236 * can represent anything you like. 1237 * @param nanosTimeout the maximum number of nanoseconds to wait 1238 * @return {@code true} if acquired; {@code false} if timed out 1239 * @throws InterruptedException if the current thread is interrupted 1240 */ 1241 public final boolean tryAcquireNanos(int arg, long nanosTimeout) 1242 throws InterruptedException { 1243 if (Thread.interrupted()) 1244 throw new InterruptedException(); 1245 return tryAcquire(arg) || 1246 doAcquireNanos(arg, nanosTimeout); 1247 } 1248 1249 /** 1250 * Releases in exclusive mode. Implemented by unblocking one or 1251 * more threads if {@link #tryRelease} returns true. 1252 * This method can be used to implement method {@link Lock#unlock}. 1253 * 1254 * @param arg the release argument. This value is conveyed to 1255 * {@link #tryRelease} but is otherwise uninterpreted and 1256 * can represent anything you like. 1257 * @return the value returned from {@link #tryRelease} 1258 */ 1259 public final boolean release(int arg) { 1260 if (tryRelease(arg)) { 1261 Node h = head; 1262 if (h != null && h.waitStatus != 0) 1263 unparkSuccessor(h); 1264 return true; 1265 } 1266 return false; 1267 } 1268 1269 /** 1270 * Acquires in shared mode, ignoring interrupts. Implemented by 1271 * first invoking at least once {@link #tryAcquireShared}, 1272 * returning on success. Otherwise the thread is queued, possibly 1273 * repeatedly blocking and unblocking, invoking {@link 1274 * #tryAcquireShared} until success. 1275 * 1276 * @param arg the acquire argument. This value is conveyed to 1277 * {@link #tryAcquireShared} but is otherwise uninterpreted 1278 * and can represent anything you like. 1279 */ 1280 public final void acquireShared(int arg) { 1281 if (tryAcquireShared(arg) < 0) 1282 doAcquireShared(arg); 1283 } 1284 1285 /** 1286 * Acquires in shared mode, aborting if interrupted. Implemented 1287 * by first checking interrupt status, then invoking at least once 1288 * {@link #tryAcquireShared}, returning on success. Otherwise the 1289 * thread is queued, possibly repeatedly blocking and unblocking, 1290 * invoking {@link #tryAcquireShared} until success or the thread 1291 * is interrupted. 1292 * @param arg the acquire argument 1293 * This value is conveyed to {@link #tryAcquireShared} but is 1294 * otherwise uninterpreted and can represent anything 1295 * you like. 1296 * @throws InterruptedException if the current thread is interrupted 1297 */ 1298 public final void acquireSharedInterruptibly(int arg) 1299 throws InterruptedException { 1300 if (Thread.interrupted()) 1301 throw new InterruptedException(); 1302 if (tryAcquireShared(arg) < 0) 1303 doAcquireSharedInterruptibly(arg); 1304 } 1305 1306 /** 1307 * Attempts to acquire in shared mode, aborting if interrupted, and 1308 * failing if the given timeout elapses. Implemented by first 1309 * checking interrupt status, then invoking at least once {@link 1310 * #tryAcquireShared}, returning on success. Otherwise, the 1311 * thread is queued, possibly repeatedly blocking and unblocking, 1312 * invoking {@link #tryAcquireShared} until success or the thread 1313 * is interrupted or the timeout elapses. 1314 * 1315 * @param arg the acquire argument. This value is conveyed to 1316 * {@link #tryAcquireShared} but is otherwise uninterpreted 1317 * and can represent anything you like. 1318 * @param nanosTimeout the maximum number of nanoseconds to wait 1319 * @return {@code true} if acquired; {@code false} if timed out 1320 * @throws InterruptedException if the current thread is interrupted 1321 */ 1322 public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) 1323 throws InterruptedException { 1324 if (Thread.interrupted()) 1325 throw new InterruptedException(); 1326 return tryAcquireShared(arg) >= 0 || 1327 doAcquireSharedNanos(arg, nanosTimeout); 1328 } 1329 1330 /** 1331 * Releases in shared mode. Implemented by unblocking one or more 1332 * threads if {@link #tryReleaseShared} returns true. 1333 * 1334 * @param arg the release argument. This value is conveyed to 1335 * {@link #tryReleaseShared} but is otherwise uninterpreted 1336 * and can represent anything you like. 1337 * @return the value returned from {@link #tryReleaseShared} 1338 */ 1339 public final boolean releaseShared(int arg) { 1340 if (tryReleaseShared(arg)) { 1341 doReleaseShared(); 1342 return true; 1343 } 1344 return false; 1345 } 1346 1347 // Queue inspection methods 1348 1349 /** 1350 * Queries whether any threads are waiting to acquire. Note that 1351 * because cancellations due to interrupts and timeouts may occur 1352 * at any time, a {@code true} return does not guarantee that any 1353 * other thread will ever acquire. 1354 * 1355 * <p>In this implementation, this operation returns in 1356 * constant time. 1357 * 1358 * @return {@code true} if there may be other threads waiting to acquire 1359 */ 1360 public final boolean hasQueuedThreads() { 1361 return head != tail; 1362 } 1363 1364 /** 1365 * Queries whether any threads have ever contended to acquire this 1366 * synchronizer; that is if an acquire method has ever blocked. 1367 * 1368 * <p>In this implementation, this operation returns in 1369 * constant time. 1370 * 1371 * @return {@code true} if there has ever been contention 1372 */ 1373 public final boolean hasContended() { 1374 return head != null; 1375 } 1376 1377 /** 1378 * Returns the first (longest-waiting) thread in the queue, or 1379 * {@code null} if no threads are currently queued. 1380 * 1381 * <p>In this implementation, this operation normally returns in 1382 * constant time, but may iterate upon contention if other threads are 1383 * concurrently modifying the queue. 1384 * 1385 * @return the first (longest-waiting) thread in the queue, or 1386 * {@code null} if no threads are currently queued 1387 */ 1388 public final Thread getFirstQueuedThread() { 1389 // handle only fast path, else relay 1390 return (head == tail) ? null : fullGetFirstQueuedThread(); 1391 } 1392 1393 /** 1394 * Version of getFirstQueuedThread called when fastpath fails 1395 */ 1396 private Thread fullGetFirstQueuedThread() { 1397 /* 1398 * The first node is normally head.next. Try to get its 1399 * thread field, ensuring consistent reads: If thread 1400 * field is nulled out or s.prev is no longer head, then 1401 * some other thread(s) concurrently performed setHead in 1402 * between some of our reads. We try this twice before 1403 * resorting to traversal. 1404 */ 1405 Node h, s; 1406 Thread st; 1407 if (((h = head) != null && (s = h.next) != null && 1408 s.prev == head && (st = s.thread) != null) || 1409 ((h = head) != null && (s = h.next) != null && 1410 s.prev == head && (st = s.thread) != null)) 1411 return st; 1412 1413 /* 1414 * Head's next field might not have been set yet, or may have 1415 * been unset after setHead. So we must check to see if tail 1416 * is actually first node. If not, we continue on, safely 1417 * traversing from tail back to head to find first, 1418 * guaranteeing termination. 1419 */ 1420 1421 Node t = tail; 1422 Thread firstThread = null; 1423 while (t != null && t != head) { 1424 Thread tt = t.thread; 1425 if (tt != null) 1426 firstThread = tt; 1427 t = t.prev; 1428 } 1429 return firstThread; 1430 } 1431 1432 /** 1433 * Returns true if the given thread is currently queued. 1434 * 1435 * <p>This implementation traverses the queue to determine 1436 * presence of the given thread. 1437 * 1438 * @param thread the thread 1439 * @return {@code true} if the given thread is on the queue 1440 * @throws NullPointerException if the thread is null 1441 */ 1442 public final boolean isQueued(Thread thread) { 1443 if (thread == null) 1444 throw new NullPointerException(); 1445 for (Node p = tail; p != null; p = p.prev) 1446 if (p.thread == thread) 1447 return true; 1448 return false; 1449 } 1450 1451 /** 1452 * Returns {@code true} if the apparent first queued thread, if one 1453 * exists, is waiting in exclusive mode. If this method returns 1454 * {@code true}, and the current thread is attempting to acquire in 1455 * shared mode (that is, this method is invoked from {@link 1456 * #tryAcquireShared}) then it is guaranteed that the current thread 1457 * is not the first queued thread. Used only as a heuristic in 1458 * ReentrantReadWriteLock. 1459 */ 1460 final boolean apparentlyFirstQueuedIsExclusive() { 1461 Node h, s; 1462 return (h = head) != null && 1463 (s = h.next) != null && 1464 !s.isShared() && 1465 s.thread != null; 1466 } 1467 1468 /** 1469 * Queries whether any threads have been waiting to acquire longer 1470 * than the current thread. 1471 * 1472 * <p>An invocation of this method is equivalent to (but may be 1473 * more efficient than): 1474 * <pre> {@code 1475 * getFirstQueuedThread() != Thread.currentThread() && 1476 * hasQueuedThreads()}</pre> 1477 * 1478 * <p>Note that because cancellations due to interrupts and 1479 * timeouts may occur at any time, a {@code true} return does not 1480 * guarantee that some other thread will acquire before the current 1481 * thread. Likewise, it is possible for another thread to win a 1482 * race to enqueue after this method has returned {@code false}, 1483 * due to the queue being empty. 1484 * 1485 * <p>This method is designed to be used by a fair synchronizer to 1486 * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. 1487 * Such a synchronizer's {@link #tryAcquire} method should return 1488 * {@code false}, and its {@link #tryAcquireShared} method should 1489 * return a negative value, if this method returns {@code true} 1490 * (unless this is a reentrant acquire). For example, the {@code 1491 * tryAcquire} method for a fair, reentrant, exclusive mode 1492 * synchronizer might look like this: 1493 * 1494 * <pre> {@code 1495 * protected boolean tryAcquire(int arg) { 1496 * if (isHeldExclusively()) { 1497 * // A reentrant acquire; increment hold count 1498 * return true; 1499 * } else if (hasQueuedPredecessors()) { 1500 * return false; 1501 * } else { 1502 * // try to acquire normally 1503 * } 1504 * }}</pre> 1505 * 1506 * @return {@code true} if there is a queued thread preceding the 1507 * current thread, and {@code false} if the current thread 1508 * is at the head of the queue or the queue is empty 1509 * @since 1.7 1510 */ 1511 public final boolean hasQueuedPredecessors() { 1512 // The correctness of this depends on head being initialized 1513 // before tail and on head.next being accurate if the current 1514 // thread is first in queue. 1515 Node t = tail; // Read fields in reverse initialization order 1516 Node h = head; 1517 Node s; 1518 return h != t && 1519 ((s = h.next) == null || s.thread != Thread.currentThread()); 1520 } 1521 1522 1523 // Instrumentation and monitoring methods 1524 1525 /** 1526 * Returns an estimate of the number of threads waiting to 1527 * acquire. The value is only an estimate because the number of 1528 * threads may change dynamically while this method traverses 1529 * internal data structures. This method is designed for use in 1530 * monitoring system state, not for synchronization 1531 * control. 1532 * 1533 * @return the estimated number of threads waiting to acquire 1534 */ 1535 public final int getQueueLength() { 1536 int n = 0; 1537 for (Node p = tail; p != null; p = p.prev) { 1538 if (p.thread != null) 1539 ++n; 1540 } 1541 return n; 1542 } 1543 1544 /** 1545 * Returns a collection containing threads that may be waiting to 1546 * acquire. Because the actual set of threads may change 1547 * dynamically while constructing this result, the returned 1548 * collection is only a best-effort estimate. The elements of the 1549 * returned collection are in no particular order. This method is 1550 * designed to facilitate construction of subclasses that provide 1551 * more extensive monitoring facilities. 1552 * 1553 * @return the collection of threads 1554 */ 1555 public final Collection<Thread> getQueuedThreads() { 1556 ArrayList<Thread> list = new ArrayList<Thread>(); 1557 for (Node p = tail; p != null; p = p.prev) { 1558 Thread t = p.thread; 1559 if (t != null) 1560 list.add(t); 1561 } 1562 return list; 1563 } 1564 1565 /** 1566 * Returns a collection containing threads that may be waiting to 1567 * acquire in exclusive mode. This has the same properties 1568 * as {@link #getQueuedThreads} except that it only returns 1569 * those threads waiting due to an exclusive acquire. 1570 * 1571 * @return the collection of threads 1572 */ 1573 public final Collection<Thread> getExclusiveQueuedThreads() { 1574 ArrayList<Thread> list = new ArrayList<Thread>(); 1575 for (Node p = tail; p != null; p = p.prev) { 1576 if (!p.isShared()) { 1577 Thread t = p.thread; 1578 if (t != null) 1579 list.add(t); 1580 } 1581 } 1582 return list; 1583 } 1584 1585 /** 1586 * Returns a collection containing threads that may be waiting to 1587 * acquire in shared mode. This has the same properties 1588 * as {@link #getQueuedThreads} except that it only returns 1589 * those threads waiting due to a shared acquire. 1590 * 1591 * @return the collection of threads 1592 */ 1593 public final Collection<Thread> getSharedQueuedThreads() { 1594 ArrayList<Thread> list = new ArrayList<Thread>(); 1595 for (Node p = tail; p != null; p = p.prev) { 1596 if (p.isShared()) { 1597 Thread t = p.thread; 1598 if (t != null) 1599 list.add(t); 1600 } 1601 } 1602 return list; 1603 } 1604 1605 /** 1606 * Returns a string identifying this synchronizer, as well as its state. 1607 * The state, in brackets, includes the String {@code "State ="} 1608 * followed by the current value of {@link #getState}, and either 1609 * {@code "nonempty"} or {@code "empty"} depending on whether the 1610 * queue is empty. 1611 * 1612 * @return a string identifying this synchronizer, as well as its state 1613 */ 1614 public String toString() { 1615 int s = getState(); 1616 String q = hasQueuedThreads() ? "non" : ""; 1617 return super.toString() + 1618 "[State = " + s + ", " + q + "empty queue]"; 1619 } 1620 1621 1622 // Internal support methods for Conditions 1623 1624 /** 1625 * Returns true if a node, always one that was initially placed on 1626 * a condition queue, is now waiting to reacquire on sync queue. 1627 * @param node the node 1628 * @return true if is reacquiring 1629 */ 1630 final boolean isOnSyncQueue(Node node) { 1631 if (node.waitStatus == Node.CONDITION || node.prev == null) 1632 return false; 1633 if (node.next != null) // If has successor, it must be on queue 1634 return true; 1635 /* 1636 * node.prev can be non-null, but not yet on queue because 1637 * the CAS to place it on queue can fail. So we have to 1638 * traverse from tail to make sure it actually made it. It 1639 * will always be near the tail in calls to this method, and 1640 * unless the CAS failed (which is unlikely), it will be 1641 * there, so we hardly ever traverse much. 1642 */ 1643 return findNodeFromTail(node); 1644 } 1645 1646 /** 1647 * Returns true if node is on sync queue by searching backwards from tail. 1648 * Called only when needed by isOnSyncQueue. 1649 * @return true if present 1650 */ 1651 private boolean findNodeFromTail(Node node) { 1652 Node t = tail; 1653 for (;;) { 1654 if (t == node) 1655 return true; 1656 if (t == null) 1657 return false; 1658 t = t.prev; 1659 } 1660 } 1661 1662 /** 1663 * Transfers a node from a condition queue onto sync queue. 1664 * Returns true if successful. 1665 * @param node the node 1666 * @return true if successfully transferred (else the node was 1667 * cancelled before signal). 1668 */ 1669 final boolean transferForSignal(Node node) { 1670 /* 1671 * If cannot change waitStatus, the node has been cancelled. 1672 */ 1673 if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) 1674 return false; 1675 1676 /* 1677 * Splice onto queue and try to set waitStatus of predecessor to 1678 * indicate that thread is (probably) waiting. If cancelled or 1679 * attempt to set waitStatus fails, wake up to resync (in which 1680 * case the waitStatus can be transiently and harmlessly wrong). 1681 */ 1682 Node p = enq(node); 1683 int ws = p.waitStatus; 1684 if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) 1685 LockSupport.unpark(node.thread); 1686 return true; 1687 } 1688 1689 /** 1690 * Transfers node, if necessary, to sync queue after a cancelled 1691 * wait. Returns true if thread was cancelled before being 1692 * signalled. 1693 * @param current the waiting thread 1694 * @param node its node 1695 * @return true if cancelled before the node was signalled 1696 */ 1697 final boolean transferAfterCancelledWait(Node node) { 1698 if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { 1699 enq(node); 1700 return true; 1701 } 1702 /* 1703 * If we lost out to a signal(), then we can't proceed 1704 * until it finishes its enq(). Cancelling during an 1705 * incomplete transfer is both rare and transient, so just 1706 * spin. 1707 */ 1708 while (!isOnSyncQueue(node)) 1709 Thread.yield(); 1710 return false; 1711 } 1712 1713 /** 1714 * Invokes release with current state value; returns saved state. 1715 * Cancels node and throws exception on failure. 1716 * @param node the condition node for this wait 1717 * @return previous sync state 1718 */ 1719 final int fullyRelease(Node node) { 1720 boolean failed = true; 1721 try { 1722 int savedState = getState(); 1723 if (release(savedState)) { 1724 failed = false; 1725 return savedState; 1726 } else { 1727 throw new IllegalMonitorStateException(); 1728 } 1729 } finally { 1730 if (failed) 1731 node.waitStatus = Node.CANCELLED; 1732 } 1733 } 1734 1735 // Instrumentation methods for conditions 1736 1737 /** 1738 * Queries whether the given ConditionObject 1739 * uses this synchronizer as its lock. 1740 * 1741 * @param condition the condition 1742 * @return <tt>true</tt> if owned 1743 * @throws NullPointerException if the condition is null 1744 */ 1745 public final boolean owns(ConditionObject condition) { 1746 if (condition == null) 1747 throw new NullPointerException(); 1748 return condition.isOwnedBy(this); 1749 } 1750 1751 /** 1752 * Queries whether any threads are waiting on the given condition 1753 * associated with this synchronizer. Note that because timeouts 1754 * and interrupts may occur at any time, a <tt>true</tt> return 1755 * does not guarantee that a future <tt>signal</tt> will awaken 1756 * any threads. This method is designed primarily for use in 1757 * monitoring of the system state. 1758 * 1759 * @param condition the condition 1760 * @return <tt>true</tt> if there are any waiting threads 1761 * @throws IllegalMonitorStateException if exclusive synchronization 1762 * is not held 1763 * @throws IllegalArgumentException if the given condition is 1764 * not associated with this synchronizer 1765 * @throws NullPointerException if the condition is null 1766 */ 1767 public final boolean hasWaiters(ConditionObject condition) { 1768 if (!owns(condition)) 1769 throw new IllegalArgumentException("Not owner"); 1770 return condition.hasWaiters(); 1771 } 1772 1773 /** 1774 * Returns an estimate of the number of threads waiting on the 1775 * given condition associated with this synchronizer. Note that 1776 * because timeouts and interrupts may occur at any time, the 1777 * estimate serves only as an upper bound on the actual number of 1778 * waiters. This method is designed for use in monitoring of the 1779 * system state, not for synchronization control. 1780 * 1781 * @param condition the condition 1782 * @return the estimated number of waiting threads 1783 * @throws IllegalMonitorStateException if exclusive synchronization 1784 * is not held 1785 * @throws IllegalArgumentException if the given condition is 1786 * not associated with this synchronizer 1787 * @throws NullPointerException if the condition is null 1788 */ 1789 public final int getWaitQueueLength(ConditionObject condition) { 1790 if (!owns(condition)) 1791 throw new IllegalArgumentException("Not owner"); 1792 return condition.getWaitQueueLength(); 1793 } 1794 1795 /** 1796 * Returns a collection containing those threads that may be 1797 * waiting on the given condition associated with this 1798 * synchronizer. Because the actual set of threads may change 1799 * dynamically while constructing this result, the returned 1800 * collection is only a best-effort estimate. The elements of the 1801 * returned collection are in no particular order. 1802 * 1803 * @param condition the condition 1804 * @return the collection of threads 1805 * @throws IllegalMonitorStateException if exclusive synchronization 1806 * is not held 1807 * @throws IllegalArgumentException if the given condition is 1808 * not associated with this synchronizer 1809 * @throws NullPointerException if the condition is null 1810 */ 1811 public final Collection<Thread> getWaitingThreads(ConditionObject condition) { 1812 if (!owns(condition)) 1813 throw new IllegalArgumentException("Not owner"); 1814 return condition.getWaitingThreads(); 1815 } 1816 1817 /** 1818 * Condition implementation for a {@link 1819 * AbstractQueuedSynchronizer} serving as the basis of a {@link 1820 * Lock} implementation. 1821 * 1822 * <p>Method documentation for this class describes mechanics, 1823 * not behavioral specifications from the point of view of Lock 1824 * and Condition users. Exported versions of this class will in 1825 * general need to be accompanied by documentation describing 1826 * condition semantics that rely on those of the associated 1827 * <tt>AbstractQueuedSynchronizer</tt>. 1828 * 1829 * <p>This class is Serializable, but all fields are transient, 1830 * so deserialized conditions have no waiters. 1831 */ 1832 public class ConditionObject implements Condition, java.io.Serializable { 1833 private static final long serialVersionUID = 1173984872572414699L; 1834 /** First node of condition queue. */ 1835 private transient Node firstWaiter; 1836 /** Last node of condition queue. */ 1837 private transient Node lastWaiter; 1838 1839 /** 1840 * Creates a new <tt>ConditionObject</tt> instance. 1841 */ 1842 public ConditionObject() { } 1843 1844 // Internal methods 1845 1846 /** 1847 * Adds a new waiter to wait queue. 1848 * @return its new wait node 1849 */ 1850 private Node addConditionWaiter() { 1851 Node t = lastWaiter; 1852 // If lastWaiter is cancelled, clean out. 1853 if (t != null && t.waitStatus != Node.CONDITION) { 1854 unlinkCancelledWaiters(); 1855 t = lastWaiter; 1856 } 1857 Node node = new Node(Thread.currentThread(), Node.CONDITION); 1858 if (t == null) 1859 firstWaiter = node; 1860 else 1861 t.nextWaiter = node; 1862 lastWaiter = node; 1863 return node; 1864 } 1865 1866 /** 1867 * Removes and transfers nodes until hit non-cancelled one or 1868 * null. Split out from signal in part to encourage compilers 1869 * to inline the case of no waiters. 1870 * @param first (non-null) the first node on condition queue 1871 */ 1872 private void doSignal(Node first) { 1873 do { 1874 if ( (firstWaiter = first.nextWaiter) == null) 1875 lastWaiter = null; 1876 first.nextWaiter = null; 1877 } while (!transferForSignal(first) && 1878 (first = firstWaiter) != null); 1879 } 1880 1881 /** 1882 * Removes and transfers all nodes. 1883 * @param first (non-null) the first node on condition queue 1884 */ 1885 private void doSignalAll(Node first) { 1886 lastWaiter = firstWaiter = null; 1887 do { 1888 Node next = first.nextWaiter; 1889 first.nextWaiter = null; 1890 transferForSignal(first); 1891 first = next; 1892 } while (first != null); 1893 } 1894 1895 /** 1896 * Unlinks cancelled waiter nodes from condition queue. 1897 * Called only while holding lock. This is called when 1898 * cancellation occurred during condition wait, and upon 1899 * insertion of a new waiter when lastWaiter is seen to have 1900 * been cancelled. This method is needed to avoid garbage 1901 * retention in the absence of signals. So even though it may 1902 * require a full traversal, it comes into play only when 1903 * timeouts or cancellations occur in the absence of 1904 * signals. It traverses all nodes rather than stopping at a 1905 * particular target to unlink all pointers to garbage nodes 1906 * without requiring many re-traversals during cancellation 1907 * storms. 1908 */ 1909 private void unlinkCancelledWaiters() { 1910 Node t = firstWaiter; 1911 Node trail = null; 1912 while (t != null) { 1913 Node next = t.nextWaiter; 1914 if (t.waitStatus != Node.CONDITION) { 1915 t.nextWaiter = null; 1916 if (trail == null) 1917 firstWaiter = next; 1918 else 1919 trail.nextWaiter = next; 1920 if (next == null) 1921 lastWaiter = trail; 1922 } 1923 else 1924 trail = t; 1925 t = next; 1926 } 1927 } 1928 1929 // public methods 1930 1931 /** 1932 * Moves the longest-waiting thread, if one exists, from the 1933 * wait queue for this condition to the wait queue for the 1934 * owning lock. 1935 * 1936 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 1937 * returns {@code false} 1938 */ 1939 public final void signal() { 1940 if (!isHeldExclusively()) 1941 throw new IllegalMonitorStateException(); 1942 Node first = firstWaiter; 1943 if (first != null) 1944 doSignal(first); 1945 } 1946 1947 /** 1948 * Moves all threads from the wait queue for this condition to 1949 * the wait queue for the owning lock. 1950 * 1951 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 1952 * returns {@code false} 1953 */ 1954 public final void signalAll() { 1955 if (!isHeldExclusively()) 1956 throw new IllegalMonitorStateException(); 1957 Node first = firstWaiter; 1958 if (first != null) 1959 doSignalAll(first); 1960 } 1961 1962 /** 1963 * Implements uninterruptible condition wait. 1964 * <ol> 1965 * <li> Save lock state returned by {@link #getState}. 1966 * <li> Invoke {@link #release} with 1967 * saved state as argument, throwing 1968 * IllegalMonitorStateException if it fails. 1969 * <li> Block until signalled. 1970 * <li> Reacquire by invoking specialized version of 1971 * {@link #acquire} with saved state as argument. 1972 * </ol> 1973 */ 1974 public final void awaitUninterruptibly() { 1975 Node node = addConditionWaiter(); 1976 int savedState = fullyRelease(node); 1977 boolean interrupted = false; 1978 while (!isOnSyncQueue(node)) { 1979 LockSupport.park(this); 1980 if (Thread.interrupted()) 1981 interrupted = true; 1982 } 1983 if (acquireQueued(node, savedState) || interrupted) 1984 selfInterrupt(); 1985 } 1986 1987 /* 1988 * For interruptible waits, we need to track whether to throw 1989 * InterruptedException, if interrupted while blocked on 1990 * condition, versus reinterrupt current thread, if 1991 * interrupted while blocked waiting to re-acquire. 1992 */ 1993 1994 /** Mode meaning to reinterrupt on exit from wait */ 1995 private static final int REINTERRUPT = 1; 1996 /** Mode meaning to throw InterruptedException on exit from wait */ 1997 private static final int THROW_IE = -1; 1998 1999 /** 2000 * Checks for interrupt, returning THROW_IE if interrupted 2001 * before signalled, REINTERRUPT if after signalled, or 2002 * 0 if not interrupted. 2003 */ 2004 private int checkInterruptWhileWaiting(Node node) { 2005 return Thread.interrupted() ? 2006 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 2007 0; 2008 } 2009 2010 /** 2011 * Throws InterruptedException, reinterrupts current thread, or 2012 * does nothing, depending on mode. 2013 */ 2014 private void reportInterruptAfterWait(int interruptMode) 2015 throws InterruptedException { 2016 if (interruptMode == THROW_IE) 2017 throw new InterruptedException(); 2018 else if (interruptMode == REINTERRUPT) 2019 selfInterrupt(); 2020 } 2021 2022 /** 2023 * Implements interruptible condition wait. 2024 * <ol> 2025 * <li> If current thread is interrupted, throw InterruptedException. 2026 * <li> Save lock state returned by {@link #getState}. 2027 * <li> Invoke {@link #release} with 2028 * saved state as argument, throwing 2029 * IllegalMonitorStateException if it fails. 2030 * <li> Block until signalled or interrupted. 2031 * <li> Reacquire by invoking specialized version of 2032 * {@link #acquire} with saved state as argument. 2033 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2034 * </ol> 2035 */ 2036 public final void await() throws InterruptedException { 2037 if (Thread.interrupted()) 2038 throw new InterruptedException(); 2039 Node node = addConditionWaiter(); 2040 int savedState = fullyRelease(node); 2041 int interruptMode = 0; 2042 while (!isOnSyncQueue(node)) { 2043 LockSupport.park(this); 2044 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2045 break; 2046 } 2047 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2048 interruptMode = REINTERRUPT; 2049 if (node.nextWaiter != null) // clean up if cancelled 2050 unlinkCancelledWaiters(); 2051 if (interruptMode != 0) 2052 reportInterruptAfterWait(interruptMode); 2053 } 2054 2055 /** 2056 * Implements timed condition wait. 2057 * <ol> 2058 * <li> If current thread is interrupted, throw InterruptedException. 2059 * <li> Save lock state returned by {@link #getState}. 2060 * <li> Invoke {@link #release} with 2061 * saved state as argument, throwing 2062 * IllegalMonitorStateException if it fails. 2063 * <li> Block until signalled, interrupted, or timed out. 2064 * <li> Reacquire by invoking specialized version of 2065 * {@link #acquire} with saved state as argument. 2066 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2067 * </ol> 2068 */ 2069 public final long awaitNanos(long nanosTimeout) 2070 throws InterruptedException { 2071 if (Thread.interrupted()) 2072 throw new InterruptedException(); 2073 Node node = addConditionWaiter(); 2074 int savedState = fullyRelease(node); 2075 long lastTime = System.nanoTime(); 2076 int interruptMode = 0; 2077 while (!isOnSyncQueue(node)) { 2078 if (nanosTimeout <= 0L) { 2079 transferAfterCancelledWait(node); 2080 break; 2081 } 2082 LockSupport.parkNanos(this, nanosTimeout); 2083 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2084 break; 2085 2086 long now = System.nanoTime(); 2087 nanosTimeout -= now - lastTime; 2088 lastTime = now; 2089 } 2090 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2091 interruptMode = REINTERRUPT; 2092 if (node.nextWaiter != null) 2093 unlinkCancelledWaiters(); 2094 if (interruptMode != 0) 2095 reportInterruptAfterWait(interruptMode); 2096 return nanosTimeout - (System.nanoTime() - lastTime); 2097 } 2098 2099 /** 2100 * Implements absolute timed condition wait. 2101 * <ol> 2102 * <li> If current thread is interrupted, throw InterruptedException. 2103 * <li> Save lock state returned by {@link #getState}. 2104 * <li> Invoke {@link #release} with 2105 * saved state as argument, throwing 2106 * IllegalMonitorStateException if it fails. 2107 * <li> Block until signalled, interrupted, or timed out. 2108 * <li> Reacquire by invoking specialized version of 2109 * {@link #acquire} with saved state as argument. 2110 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2111 * <li> If timed out while blocked in step 4, return false, else true. 2112 * </ol> 2113 */ 2114 public final boolean awaitUntil(Date deadline) 2115 throws InterruptedException { 2116 if (deadline == null) 2117 throw new NullPointerException(); 2118 long abstime = deadline.getTime(); 2119 if (Thread.interrupted()) 2120 throw new InterruptedException(); 2121 Node node = addConditionWaiter(); 2122 int savedState = fullyRelease(node); 2123 boolean timedout = false; 2124 int interruptMode = 0; 2125 while (!isOnSyncQueue(node)) { 2126 if (System.currentTimeMillis() > abstime) { 2127 timedout = transferAfterCancelledWait(node); 2128 break; 2129 } 2130 LockSupport.parkUntil(this, abstime); 2131 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2132 break; 2133 } 2134 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2135 interruptMode = REINTERRUPT; 2136 if (node.nextWaiter != null) 2137 unlinkCancelledWaiters(); 2138 if (interruptMode != 0) 2139 reportInterruptAfterWait(interruptMode); 2140 return !timedout; 2141 } 2142 2143 /** 2144 * Implements timed condition wait. 2145 * <ol> 2146 * <li> If current thread is interrupted, throw InterruptedException. 2147 * <li> Save lock state returned by {@link #getState}. 2148 * <li> Invoke {@link #release} with 2149 * saved state as argument, throwing 2150 * IllegalMonitorStateException if it fails. 2151 * <li> Block until signalled, interrupted, or timed out. 2152 * <li> Reacquire by invoking specialized version of 2153 * {@link #acquire} with saved state as argument. 2154 * <li> If interrupted while blocked in step 4, throw InterruptedException. 2155 * <li> If timed out while blocked in step 4, return false, else true. 2156 * </ol> 2157 */ 2158 public final boolean await(long time, TimeUnit unit) 2159 throws InterruptedException { 2160 if (unit == null) 2161 throw new NullPointerException(); 2162 long nanosTimeout = unit.toNanos(time); 2163 if (Thread.interrupted()) 2164 throw new InterruptedException(); 2165 Node node = addConditionWaiter(); 2166 int savedState = fullyRelease(node); 2167 long lastTime = System.nanoTime(); 2168 boolean timedout = false; 2169 int interruptMode = 0; 2170 while (!isOnSyncQueue(node)) { 2171 if (nanosTimeout <= 0L) { 2172 timedout = transferAfterCancelledWait(node); 2173 break; 2174 } 2175 if (nanosTimeout >= spinForTimeoutThreshold) 2176 LockSupport.parkNanos(this, nanosTimeout); 2177 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) 2178 break; 2179 long now = System.nanoTime(); 2180 nanosTimeout -= now - lastTime; 2181 lastTime = now; 2182 } 2183 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) 2184 interruptMode = REINTERRUPT; 2185 if (node.nextWaiter != null) 2186 unlinkCancelledWaiters(); 2187 if (interruptMode != 0) 2188 reportInterruptAfterWait(interruptMode); 2189 return !timedout; 2190 } 2191 2192 // support for instrumentation 2193 2194 /** 2195 * Returns true if this condition was created by the given 2196 * synchronization object. 2197 * 2198 * @return {@code true} if owned 2199 */ 2200 final boolean isOwnedBy(AbstractQueuedSynchronizer sync) { 2201 return sync == AbstractQueuedSynchronizer.this; 2202 } 2203 2204 /** 2205 * Queries whether any threads are waiting on this condition. 2206 * Implements {@link AbstractQueuedSynchronizer#hasWaiters}. 2207 * 2208 * @return {@code true} if there are any waiting threads 2209 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2210 * returns {@code false} 2211 */ 2212 protected final boolean hasWaiters() { 2213 if (!isHeldExclusively()) 2214 throw new IllegalMonitorStateException(); 2215 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2216 if (w.waitStatus == Node.CONDITION) 2217 return true; 2218 } 2219 return false; 2220 } 2221 2222 /** 2223 * Returns an estimate of the number of threads waiting on 2224 * this condition. 2225 * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}. 2226 * 2227 * @return the estimated number of waiting threads 2228 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2229 * returns {@code false} 2230 */ 2231 protected final int getWaitQueueLength() { 2232 if (!isHeldExclusively()) 2233 throw new IllegalMonitorStateException(); 2234 int n = 0; 2235 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2236 if (w.waitStatus == Node.CONDITION) 2237 ++n; 2238 } 2239 return n; 2240 } 2241 2242 /** 2243 * Returns a collection containing those threads that may be 2244 * waiting on this Condition. 2245 * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}. 2246 * 2247 * @return the collection of threads 2248 * @throws IllegalMonitorStateException if {@link #isHeldExclusively} 2249 * returns {@code false} 2250 */ 2251 protected final Collection<Thread> getWaitingThreads() { 2252 if (!isHeldExclusively()) 2253 throw new IllegalMonitorStateException(); 2254 ArrayList<Thread> list = new ArrayList<Thread>(); 2255 for (Node w = firstWaiter; w != null; w = w.nextWaiter) { 2256 if (w.waitStatus == Node.CONDITION) { 2257 Thread t = w.thread; 2258 if (t != null) 2259 list.add(t); 2260 } 2261 } 2262 return list; 2263 } 2264 } 2265 2266 /** 2267 * Setup to support compareAndSet. We need to natively implement 2268 * this here: For the sake of permitting future enhancements, we 2269 * cannot explicitly subclass AtomicInteger, which would be 2270 * efficient and useful otherwise. So, as the lesser of evils, we 2271 * natively implement using hotspot intrinsics API. And while we 2272 * are at it, we do the same for other CASable fields (which could 2273 * otherwise be done with atomic field updaters). 2274 */ 2275 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2276 private static final long stateOffset; 2277 private static final long headOffset; 2278 private static final long tailOffset; 2279 private static final long waitStatusOffset; 2280 private static final long nextOffset; 2281 2282 static { 2283 try { 2284 stateOffset = unsafe.objectFieldOffset 2285 (AbstractQueuedSynchronizer.class.getDeclaredField("state")); 2286 headOffset = unsafe.objectFieldOffset 2287 (AbstractQueuedSynchronizer.class.getDeclaredField("head")); 2288 tailOffset = unsafe.objectFieldOffset 2289 (AbstractQueuedSynchronizer.class.getDeclaredField("tail")); 2290 waitStatusOffset = unsafe.objectFieldOffset 2291 (Node.class.getDeclaredField("waitStatus")); 2292 nextOffset = unsafe.objectFieldOffset 2293 (Node.class.getDeclaredField("next")); 2294 2295 } catch (Exception ex) { throw new Error(ex); } 2296 } 2297 2298 /** 2299 * CAS head field. Used only by enq. 2300 */ 2301 private final boolean compareAndSetHead(Node update) { 2302 return unsafe.compareAndSwapObject(this, headOffset, null, update); 2303 } 2304 2305 /** 2306 * CAS tail field. Used only by enq. 2307 */ 2308 private final boolean compareAndSetTail(Node expect, Node update) { 2309 return unsafe.compareAndSwapObject(this, tailOffset, expect, update); 2310 } 2311 2312 /** 2313 * CAS waitStatus field of a node. 2314 */ 2315 private static final boolean compareAndSetWaitStatus(Node node, 2316 int expect, 2317 int update) { 2318 return unsafe.compareAndSwapInt(node, waitStatusOffset, 2319 expect, update); 2320 } 2321 2322 /** 2323 * CAS next field of a node. 2324 */ 2325 private static final boolean compareAndSetNext(Node node, 2326 Node expect, 2327 Node update) { 2328 return unsafe.compareAndSwapObject(node, nextOffset, expect, update); 2329 } 2330 }
其中,共享锁源码相关的代码如下:
public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; // ReentrantReadWriteLock的AQS对象 private final Sync sync; protected ReadLock(ReentrantReadWriteLock lock) { sync = lock.sync; } // 获取“共享锁” public void lock() { sync.acquireShared(1); } // 如果线程是中断状态,则抛出一场,否则尝试获取共享锁。 public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } // 尝试获取“共享锁” public boolean tryLock() { return sync.tryReadLock(); } // 在指定时间内,尝试获取“共享锁” public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } // 释放“共享锁” public void unlock() { sync.releaseShared(1); } // 新建条件 public Condition newCondition() { throw new UnsupportedOperationException(); } public String toString() { int r = sync.getReadLockCount(); return super.toString() + "[Read locks = " + r + "]"; } }
说明:
ReadLock中的sync是一个Sync对象,Sync继承于AQS类,即Sync就是一个锁。ReentrantReadWriteLock中也有一个Sync对象,而且ReadLock中的sync和ReentrantReadWriteLock中的sync是对应关系。即ReentrantReadWriteLock和ReadLock共享同一个AQS对象,共享同一把锁。
ReentrantReadWriteLock中Sync的定义如下:
final Sync sync;
下面,分别从“获取共享锁”和“释放共享锁”两个方面对共享锁进行说明。
获取共享锁
获取共享锁的思想(即lock函数的步骤),是先通过tryAcquireShared()尝试获取共享锁。尝试成功的话,则直接返回;尝试失败的话,则通过doAcquireShared()不断的循环并尝试获取锁,若有需要,则阻塞等待。doAcquireShared()在循环中每次尝试获取锁时,都是通过tryAcquireShared()来进行尝试的。下面看看“获取共享锁”的详细流程。
1. lock()
lock()在ReadLock中,源码如下:
public void lock() { sync.acquireShared(1); }
2. acquireShared()
Sync继承于AQS,acquireShared()定义在AQS中。源码如下:
public final void acquireShared(int arg) { if (tryAcquireShared(arg) < 0) doAcquireShared(arg); }
说明:acquireShared()首先会通过tryAcquireShared()来尝试获取锁。
尝试成功的话,则不再做任何动作(因为已经成功获取到锁了)。
尝试失败的话,则通过doAcquireShared()来获取锁。doAcquireShared()会获取到锁了才返回。
3. tryAcquireShared()
tryAcquireShared()定义在ReentrantReadWriteLock.java的Sync中,源码如下:
protected final int tryAcquireShared(int unused) { Thread current = Thread.currentThread(); // 获取“锁”的状态 int c = getState(); // 如果“锁”是“互斥锁”,并且获取锁的线程不是current线程;则返回-1。 if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; // 获取“读取锁”的共享计数 int r = sharedCount(c); // 如果“不需要阻塞等待”,并且“读取锁”的共享计数小于MAX_COUNT; // 则通过CAS函数更新“锁的状态”,将“读取锁”的共享计数+1。 if (!readerShouldBlock() && r < MAX_COUNT && compareAndSetState(c, c + SHARED_UNIT)) { // 第1次获取“读取锁”。 if (r == 0) { firstReader = current; firstReaderHoldCount = 1; // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程 } else if (firstReader == current) { firstReaderHoldCount++; } else { // HoldCounter是用来统计该线程获取“读取锁”的次数。 HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) cachedHoldCounter = rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); // 将该线程获取“读取锁”的次数+1。 rh.count++; } return 1; } return fullTryAcquireShared(current); }
说明:tryAcquireShared()的作用是尝试获取“共享锁”。
如果在尝试获取锁时,“不需要阻塞等待”并且“读取锁的共享计数小于MAX_COUNT”,则直接通过CAS函数更新“读取锁的共享计数”,以及将“当前线程获取读取锁的次数+1”。
否则,通过fullTryAcquireShared()获取读取锁。
4. fullTryAcquireShared()
fullTryAcquireShared()在ReentrantReadWriteLock中定义,源码如下:
final int fullTryAcquireShared(Thread current) { HoldCounter rh = null; for (;;) { // 获取“锁”的状态 int c = getState(); // 如果“锁”是“互斥锁”,并且获取锁的线程不是current线程;则返回-1。 if (exclusiveCount(c) != 0) { if (getExclusiveOwnerThread() != current) return -1; // 如果“需要阻塞等待”。 // (01) 当“需要阻塞等待”的线程是第1个获取锁的线程的话,则继续往下执行。 // (02) 当“需要阻塞等待”的线程获取锁的次数=0时,则返回-1。 } else if (readerShouldBlock()) { // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程 if (firstReader == current) { } else { if (rh == null) { rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) { rh = readHolds.get(); if (rh.count == 0) readHolds.remove(); } } // 如果当前线程获取锁的计数=0,则返回-1。 if (rh.count == 0) return -1; } } // 如果“不需要阻塞等待”,则获取“读取锁”的共享统计数; // 如果共享统计数超过MAX_COUNT,则抛出异常。 if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); // 将线程获取“读取锁”的次数+1。 if (compareAndSetState(c, c + SHARED_UNIT)) { // 如果是第1次获取“读取锁”,则更新firstReader和firstReaderHoldCount。 if (sharedCount(c) == 0) { firstReader = current; firstReaderHoldCount = 1; // 如果想要获取锁的线程(current)是第1个获取锁(firstReader)的线程, // 则将firstReaderHoldCount+1。 } else if (firstReader == current) { firstReaderHoldCount++; } else { if (rh == null) rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); // 更新线程的获取“读取锁”的共享计数 rh.count++; cachedHoldCounter = rh; // cache for release } return 1; } } }
说明:fullTryAcquireShared()会根据“是否需要阻塞等待”,“读取锁的共享计数是否超过限制”等等进行处理。如果不需要阻塞等待,并且锁的共享计数没有超过限制,则通过CAS尝试获取锁,并返回1。
5. doAcquireShared()
doAcquireShared()定义在AQS函数中,源码如下:
private void doAcquireShared(int arg) { // addWaiter(Node.SHARED)的作用是,创建“当前线程”对应的节点,并将该线程添加到CLH队列中。 final Node node = addWaiter(Node.SHARED); boolean failed = true; try { boolean interrupted = false; for (;;) { // 获取“node”的前一节点 final Node p = node.predecessor(); // 如果“当前线程”是CLH队列的表头,则尝试获取共享锁。 if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC if (interrupted) selfInterrupt(); failed = false; return; } } // 如果“当前线程”不是CLH队列的表头,则通过shouldParkAfterFailedAcquire()判断是否需要等待, // 需要的话,则通过parkAndCheckInterrupt()进行阻塞等待。若阻塞等待过程中,线程被中断过,则设置interrupted为true。 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } }
说明:doAcquireShared()的作用是获取共享锁。
它会首先创建线程对应的CLH队列的节点,然后将该节点添加到CLH队列中。CLH队列是管理获取锁的等待线程的队列。
如果“当前线程”是CLH队列的表头,则尝试获取共享锁;否则,则需要通过shouldParkAfterFailedAcquire()判断是否阻塞等待,需要的话,则通过parkAndCheckInterrupt()进行阻塞等待。
doAcquireShared()会通过for循环,不断的进行上面的操作;目的就是获取共享锁。需要注意的是:doAcquireShared()在每一次尝试获取锁时,是通过tryAcquireShared()来执行的!
shouldParkAfterFailedAcquire(), parkAndCheckInterrupt()等函数已经在“Java多线程系列--“JUC锁”03之 公平锁(一) ”中详细介绍过,这里就不再重复说明了。
释放共享锁
释放共享锁的思想,是先通过tryReleaseShared()尝试释放共享锁。尝试成功的话,则通过doReleaseShared()唤醒“其他等待获取共享锁的线程”,并返回true;否则的话,返回flase。
1. unlock()
public void unlock() { sync.releaseShared(1); }
说明:该函数实际上调用releaseShared(1)释放共享锁。
2. releaseShared()
releaseShared()在AQS中实现,源码如下:
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; }
说明:releaseShared()的目的是让当前线程释放它所持有的共享锁。
它首先会通过tryReleaseShared()去尝试释放共享锁。尝试成功,则直接返回;尝试失败,则通过doReleaseShared()去释放共享锁。
3. tryReleaseShared()
tryReleaseShared()定义在ReentrantReadWriteLock中,源码如下:
protected final boolean tryReleaseShared(int unused) { // 获取当前线程,即释放共享锁的线程。 Thread current = Thread.currentThread(); // 如果想要释放锁的线程(current)是第1个获取锁(firstReader)的线程, // 并且“第1个获取锁的线程获取锁的次数”=1,则设置firstReader为null; // 否则,将“第1个获取锁的线程的获取次数”-1。 if (firstReader == current) { // assert firstReaderHoldCount > 0; if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; // 获取rh对象,并更新“当前线程获取锁的信息”。 } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); int count = rh.count; if (count <= 1) { readHolds.remove(); if (count <= 0) throw unmatchedUnlockException(); } --rh.count; } for (;;) { // 获取锁的状态 int c = getState(); // 将锁的获取次数-1。 int nextc = c - SHARED_UNIT; // 通过CAS更新锁的状态。 if (compareAndSetState(c, nextc)) return nextc == 0; } }
说明:tryReleaseShared()的作用是尝试释放共享锁。
4. doReleaseShared()
doReleaseShared()定义在AQS中,源码如下:
private void doReleaseShared() { for (;;) { // 获取CLH队列的头节点 Node h = head; // 如果头节点不为null,并且头节点不等于tail节点。 if (h != null && h != tail) { // 获取头节点对应的线程的状态 int ws = h.waitStatus; // 如果头节点对应的线程是SIGNAL状态,则意味着“头节点的下一个节点所对应的线程”需要被unpark唤醒。 if (ws == Node.SIGNAL) { // 设置“头节点对应的线程状态”为空状态。失败的话,则继续循环。 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // 唤醒“头节点的下一个节点所对应的线程”。 unparkSuccessor(h); } // 如果头节点对应的线程是空状态,则设置“文件点对应的线程所拥有的共享锁”为其它线程获取锁的空状态。 else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } // 如果头节点发生变化,则继续循环。否则,退出循环。 if (h == head) // loop if head changed break; } }
说明:doReleaseShared()会释放“共享锁”。它会从前往后的遍历CLH队列,依次“唤醒”然后“执行”队列中每个节点对应的线程;最终的目的是让这些线程释放它们所持有的锁。
公平共享锁和非公平共享锁
和互斥锁ReentrantLock一样,ReadLock也分为公平锁和非公平锁。
公平锁和非公平锁的区别,体现在判断是否需要阻塞的函数readerShouldBlock()是不同的。
公平锁的readerShouldBlock()的源码如下:
final boolean readerShouldBlock() { return hasQueuedPredecessors(); }
在公平共享锁中,如果在当前线程的前面有其他线程在等待获取共享锁,则返回true;否则,返回false。
非公平锁的readerShouldBlock()的源码如下:
final boolean readerShouldBlock() { return apparentlyFirstQueuedIsExclusive(); }
在非公平共享锁中,它会无视当前线程的前面是否有其他线程在等待获取共享锁。只要该非公平共享锁对应的线程不为null,则返回true。
ReentrantReadWriteLock示例
1 import java.util.concurrent.locks.ReadWriteLock; 2 import java.util.concurrent.locks.ReentrantReadWriteLock; 3 4 public class ReadWriteLockTest1 { 5 6 public static void main(String[] args) { 7 // 创建账户 8 MyCount myCount = new MyCount("4238920615242830", 10000); 9 // 创建用户,并指定账户 10 User user = new User("Tommy", myCount); 11 12 // 分别启动3个“读取账户金钱”的线程 和 3个“设置账户金钱”的线程 13 for (int i=0; i<3; i++) { 14 user.getCash(); 15 user.setCash((i+1)*1000); 16 } 17 } 18 } 19 20 class User { 21 private String name; //用户名 22 private MyCount myCount; //所要操作的账户 23 private ReadWriteLock myLock; //执行操作所需的锁对象 24 25 User(String name, MyCount myCount) { 26 this.name = name; 27 this.myCount = myCount; 28 this.myLock = new ReentrantReadWriteLock(); 29 } 30 31 public void getCash() { 32 new Thread() { 33 public void run() { 34 myLock.readLock().lock(); 35 try { 36 System.out.println(Thread.currentThread().getName() +" getCash start"); 37 myCount.getCash(); 38 Thread.sleep(1); 39 System.out.println(Thread.currentThread().getName() +" getCash end"); 40 } catch (InterruptedException e) { 41 } finally { 42 myLock.readLock().unlock(); 43 } 44 } 45 }.start(); 46 } 47 48 public void setCash(final int cash) { 49 new Thread() { 50 public void run() { 51 myLock.writeLock().lock(); 52 try { 53 System.out.println(Thread.currentThread().getName() +" setCash start"); 54 myCount.setCash(cash); 55 Thread.sleep(1); 56 System.out.println(Thread.currentThread().getName() +" setCash end"); 57 } catch (InterruptedException e) { 58 } finally { 59 myLock.writeLock().unlock(); 60 } 61 } 62 }.start(); 63 } 64 } 65 66 class MyCount { 67 private String id; //账号 68 private int cash; //账户余额 69 70 MyCount(String id, int cash) { 71 this.id = id; 72 this.cash = cash; 73 } 74 75 public String getId() { 76 return id; 77 } 78 79 public void setId(String id) { 80 this.id = id; 81 } 82 83 public int getCash() { 84 System.out.println(Thread.currentThread().getName() +" getCash cash="+ cash); 85 return cash; 86 } 87 88 public void setCash(int cash) { 89 System.out.println(Thread.currentThread().getName() +" setCash cash="+ cash); 90 this.cash = cash; 91 } 92 }
运行结果:
Thread-0 getCash start Thread-2 getCash start Thread-0 getCash cash=10000 Thread-2 getCash cash=10000 Thread-0 getCash end Thread-2 getCash end Thread-1 setCash start Thread-1 setCash cash=1000 Thread-1 setCash end Thread-3 setCash start Thread-3 setCash cash=2000 Thread-3 setCash end Thread-4 getCash start Thread-4 getCash cash=2000 Thread-4 getCash end Thread-5 setCash start Thread-5 setCash cash=3000 Thread-5 setCash end
结果说明:
(01) 观察Thread0和Thread-2的运行结果,我们发现,Thread-0启动并获取到“读取锁”,在它还没运行完毕的时候,Thread-2也启动了并且也成功获取到“读取锁”。
因此,“读取锁”支持被多个线程同时获取。
(02) 观察Thread-1,Thread-3,Thread-5这三个“写入锁”的线程。只要“写入锁”被某线程获取,则该线程运行完毕了,才释放该锁。
因此,“写入锁”不支持被多个线程同时获取。