可重入读写锁 ReentrantReadWriteLock 其实基本上模拟了文件的读写锁操做。ReentrantReadWriteLock 和ReentrantLock 的差异仍是蛮大的; 可是也有不少的类似之处; ReentrantReadWriteLock 的 writerLock 其实就是至关于ReentrantLock,可是它提供更多的细腻的控制;理解什么是读锁、写锁很是重要,虽然实际工做中区分读写锁这样的细分使用场景比较少。java
ReentrantReadWriteLock 把锁进行了细化,分为了两种: 读锁和写锁。它们之间有一些限制关系:缓存
读 写
读 Y N
写 N N
并发
其中: Y 表示共享,N表示排斥(即独占)app
具体分析以下:less
/** ReadWriteLock的一个实现,支持相似于ReentrantLock的语义。 这个类有如下属性: 1 获取顺序 该类不为锁访问强加读线程、写线程优先顺序。可是,它确实支持一个可选的公平策略。 2 非公平模式(默认 当构造为非公平锁(默认状况下)时,读写锁的进入顺序是不指定的,受重入限制。持续争夺的非公平锁可能会无限期推迟一个或多个读写线程,但一般会比公平锁的吞吐量更高。 3 公平模式 当构造为公平时,线程使用大约到达顺序策略争夺进入。当当前持有的锁被释放时,等待时间最长的单个写线程将被分配到写锁,或者若是有一组读线程线程的等待时间超过全部等待的写线程,则该组将被分配到读锁。 试图获取公平的读锁的线程(非重入式),若是写锁被持有,或者有一个等待的写器线程,则会被阻止。该线程将在当前最老的等待写器线程得到并释放写锁后才会得到读锁。固然,若是一个等待的写器线程放弃了等待,留下一个或多个读线程、写线程做为队列中最长的等待线程,并释放了写锁,那么这些读写器线程将被分配到读锁。 一个试图得到公平写锁的线程(非重现性)将被阻塞,除非读锁和写锁都是空闲的(这意味着没有等待线程)。(注意,非阻塞的ReentrantReadWriteLock.ReadLock.tryLock()和ReentrantReadWriteLock.WriteLock.tryLock()方法不尊重这个公平设置,若是可能的话,会当即获取锁,而不考虑等待线程的状况。) 1 可重入性 这个锁容许读线程和写线程均可以用ReentrantLock的方式从新得到读锁或写锁。在写线程所持有的全部写锁被释放以前,不容许非重入式读写器得到读写锁。 此外,写线程能够得到读锁,但反之不行。在其余应用中,当在调用或回调方法执行读锁的过程当中持有写锁的时候,重入性是很是有用的。若是读取器试图获取写锁,它将永远不会成功。 2 锁的降级 重入也容许从写锁降级为读锁,方法是先得到写锁,再得到读锁,而后释放写锁。可是,从读锁升级到写锁是不可能的。 锁的获取中断 读锁和写锁都支持锁获取过程当中的中断。 3 条件支持 写锁提供了一个Condition实现,这个Condition实现与ReentrantLock.newCondition为ReentrantLock提供的Condition实如今写锁方面的行为是同样的。固然,这个Condition只能和写锁一块儿使用。 读锁不支持Condition,而且readLock().newCondition()会抛出UnsupportedOperationException。 4 仪器化 该类支持肯定锁是否被持有或被争用的方法。这些方法是为监控系统状态而设计的,而不是用于同步控制。 该类的序列化与内置锁的行为方式相同:不管序列化时锁的状态如何,反序列化后的锁都处于未锁状态。 使用示例。下面是一个代码草图,展现了如何在更新缓存后执行锁的降级(当以非嵌套方式处理多个锁时,异常处理特别棘手)。 * <pre> {@code * class CachedData { * Object data; * volatile boolean cacheValid; * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); * * void processCachedData() { * rwl.readLock().lock(); * if (!cacheValid) { * // Must release read lock before acquiring write lock * rwl.readLock().unlock(); * rwl.writeLock().lock(); * try { * // Recheck state because another thread might have * // acquired write lock and changed state before we did. * if (!cacheValid) { * data = ... * cacheValid = true; * } * // Downgrade by acquiring read lock before releasing write lock * rwl.readLock().lock(); * } finally { * rwl.writeLock().unlock(); // Unlock write, still hold read * } * } * * try { * use(data); * } finally { * rwl.readLock().unlock(); * } * } ReentrantReadWriteLocks能够用来改善某些类型的Collection的某些用途中的并发性。通常来讲,只有当预期集合很大,被更多的读写器线程访问,而且须要开销大于同步开销的操做时,才值得使用。例如,这里是一个使用TreeMap的类,它预计会有很大的并发访问量。 class RWDictionary { * private final Map<String, Data> m = new TreeMap<String, Data>(); * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); * private final Lock r = rwl.readLock(); * private final Lock w = rwl.writeLock(); * * public Data get(String key) { * r.lock(); * try { return m.get(key); } * finally { r.unlock(); } * } * public String[] allKeys() { * r.lock(); * try { return m.keySet().toArray(); } * finally { r.unlock(); } * } * public Data put(String key, Data value) { * w.lock(); * try { return m.put(key, value); } * finally { w.unlock(); } * } * public void clear() { * w.lock(); * try { m.clear(); } * finally { w.unlock(); } * } * }} 该锁最多支持65535个递归写锁和65535读锁。试图超过这些限制的结果是 {@link错误}从锁定方法中抛出。 我理解,基本是下面关系, Y 表示共享,N表示排斥(即独占) 读 写 读 Y N 写 N N public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable { private static final long serialVersionUID = -6992448646407690164L; /** Inner class providing readlock */ private final ReentrantReadWriteLock.ReadLock readerLock; 读锁 /** Inner class providing writelock */ private final ReentrantReadWriteLock.WriteLock writerLock; 写锁 /** Performs all synchronization mechanics */ final Sync sync; 同步器 /** * Creates a new {@code ReentrantReadWriteLock} with * default (nonfair) ordering properties. 默认是 非公平锁 */ public ReentrantReadWriteLock() { this(false); } /** * Creates a new {@code ReentrantReadWriteLock} with * the given fairness policy. 策略是指 公平 * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantReadWriteLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); readerLock = new ReadLock(this); writerLock = new WriteLock(this); } public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; } public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; } /** * Synchronization implementation for ReentrantReadWriteLock. * Subclassed into fair and nonfair versions. ReentrantReadWriteLock的同步机制的基础实现。子类分为下面的公平和非公平版本。使用AQS状态来表明锁上的持有数量。 跟ReentrantLock很是相似的作法,可是细节上不少成本; */ abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 6317671515068378041L; /* * Read vs write count extraction constants and functions. * Lock state is logically divided into two unsigned shorts: * The lower one representing the exclusive (writer) lock hold count, * and the upper the shared (reader) hold count. */ *读写计数提取的常数和函数。 * 锁定状态在逻辑上被分为两个无符号的short型数字。 * 较低的一个表明独占(写人)锁持有数,较高的表明共享的(读线程)锁持有数。 */ static final int SHARED_SHIFT = 16; static final int SHARED_UNIT = (1 << SHARED_SHIFT); 较高的int bit位 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; 最大的计数 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; 独占锁的掩码,由于独占锁是低位,而java默认为大端模式, 因此须要对独占计数 进行掩码计算; /** Returns the number of shared holds represented in count */ 返回某状态c中共享锁使用的次数 static int sharedCount(int c) { return c >>> SHARED_SHIFT; } 至关因而获取高16位,忽略低位 /** Returns the number of exclusive holds represented in count */ 返回某状态c中独占锁使用的次数 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } 至关因而获取低16位,忽略高位 /** * A counter for per-thread read hold counts. 每线程读取保持计数的计数器。 * Maintained as a ThreadLocal; cached in cachedHoldCounter 做为ThreadLocal维护;缓存在cachedHoldCounter中。 */ 顾名思义是 持有计算器; 为何不单独的使用int count,而是单独的一个类? 由于 这个类须要在ThreadLocal缓存, 也就是 ThreadLocalHoldCounter ,从ThreadLocalHoldCounter的用法可知,HoldCounter 仅仅用于 读操做的线程; 就是说每一个线程进行读操做的时候,把它的读次数加1,而且保存在那个线程的自己的变量里面。 static final class HoldCounter { int count = 0; // Use id, not reference, to avoid garbage retention 使用id,而不是引用,以免垃圾保留。 垃圾保留 是什么意思? 没法回收的垃圾! 由于不是引用,就不会致使引用计算器的变化 final long tid = getThreadId(Thread.currentThread()); } /** * ThreadLocal subclass. Easiest to explicitly define for sake * of deserialization mechanics. ThreadLocal子类。最容易显式定义的是,为了去序列化机制。 */ ThreadLocal 的做用是把变量保存在线程对象内部的map变量中,可是这个map 即ThreadLocalMap是很特殊的,它以线程做为key; 故ThreadLocal提供的方法也很特殊 它提供了get、set(非静态方法),可是都不须要指定key,由于key 就是当前执行的线程;就是说,每一个线程只可以获取本身的value,至关因而把 value 绑定到了线程上; ThreadLocal是须要初始化其内部的map对象的,仅仅在setInitialValue()、set(T value)的时候能够初始化;,每次get的时候,若是没有初始化,那么就进行初始化,即调用setInitialValue,而后调用initialValue方法,而后若有必要则建立map; ThreadLocal 还提供了remove方法,也就是把当前线程做为key,从map中删除 static final class ThreadLocalHoldCounter extends ThreadLocal<HoldCounter> { public HoldCounter initialValue() { return new HoldCounter(); 默认的读计数 固然是0 initialValue 方法提供了初始值;固然这个是按照须要来的,某些状况 也能够不用提供初始值 } } /** * The number of reentrant read locks held by current thread. * Initialized only in constructor and readObject. * Removed whenever a thread's read hold count drops to 0. * 当前线程持有的重入读锁的数量。 * 只在构造函数和readObject中初始化。 * 当线程的读取保持数降低到0时,会被移除。 */ private transient ThreadLocalHoldCounter readHolds; 把读操做计数 绑定到了线程上 /** * The hold count of the last thread to successfully acquire * readLock. This saves ThreadLocal lookup in the common case * where the next thread to release is the last one to * acquire. This is non-volatile since it is just used * as a heuristic, and would be great for threads to cache. * * <p>Can outlive the Thread for which it is caching the read * hold count, but avoids garbage retention by not retaining a * reference to the Thread. * * <p>Accessed via a benign data race; relies on the memory * model's final field and out-of-thin-air guarantees. 最后一个成功获取readLock的线程的保持数。这在下一个要释放的线程是最后一个获取的线程的状况下,能够节省ThreadLocal查找。这个是非易失性的,由于它只是做为启发式的,对于线程缓存来讲是很好的。 * <p>能够超过缓存的线程的读取保持数,但经过不保留对线程的引用来避免垃圾保留。 * * <p>经过良性的数据竞赛访问;依靠内存模型的最终字段和空投保证。 */ private transient HoldCounter cachedHoldCounter; 读锁的缓存; 缓存什么? 缓存 最后一个成功获取资源的读锁! 为何须要缓存起来? 能够节省ThreadLocal查找操做 /** * firstReader is the first thread to have acquired the read lock. * firstReaderHoldCount is firstReader's hold count. * * <p>More precisely, firstReader is the unique thread that last * changed the shared count from 0 to 1, and has not released the * read lock since then; null if there is no such thread. * * <p>Cannot cause garbage retention unless the thread terminated * without relinquishing its read locks, since tryReleaseShared 这句话难以理解xxx * sets it to null. * * <p>Accessed via a benign data race; relies on the memory * model's out-of-thin-air guarantees for references. * * <p>This allows tracking of read holds for uncontended read * locks to be very cheap. * firstReader是第一个得到读锁的线程。 * firstReaderHoldCount是firstReader的保持数。 * * <p>更准确地说,firstReader是最后一次将共享计数从0改成1的惟一线程,而且此后没有释放过读锁;若是没有这样的线程,则为空。 * <p>除非在没有放弃读锁的状况下终止线程,不然不会致使垃圾保留,由于 tryReleaseShared 将其设置为空。 * * <p>经过良性的数据竞赛访问;依赖内存模型的无中生有地来保证引用。 * * <p>这使得对无争议的读取锁的读取保持的跟踪很是便宜。 relinquish (尤指不情愿地)放弃 废除;撤回;中止 benign 良性的 仁慈的;和善的;良好的 out-of-thin-air 无中生有地 */ private transient Thread firstReader = null; 主要为了跟踪.. private transient int firstReaderHoldCount; Sync() { 内部构造器 readHolds = new ThreadLocalHoldCounter(); setState(getState()); // ensures visibility of readHolds } /* * Acquires and releases use the same code for fair and * nonfair locks, but differ in whether/how they allow barging * when queues are non-empty. */ * 获取和释放对公平锁和非公平锁 使用相同的代码,但在队列非空时 是否/怎么 容许线程的忽然闯进 有所不一样。 barging 忽然的闯入 驳船 /** * Returns true if the current thread, when trying to acquire * the read lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. 这里也是很是绕 若是当前线程 正在试图得到读锁,以及在其余有资格的状况下这样作时,因为超越其余等待的线程的策略而应当被阻止,则返回true。 所谓policy for overtaking other waiting threads,实际上是线程的追赶机制。 overtake 追上;遇上;超过;赶补(欠工) 超车;超越;追越 */ abstract boolean readerShouldBlock(); 简单说就是 读操做是否应该阻塞 /** * Returns true if the current thread, when trying to acquire * the write lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. 同上,读锁改为写锁 */ abstract boolean writerShouldBlock(); /* * Note that tryRelease and tryAcquire can be called by * Conditions. So it is possible that their arguments contain * both read and write holds that are all released during a * condition wait and re-established in tryAcquire. 注意tryRelease和tryAcquire能够被条件对象下调用,因此 这两个方法的参数可能会 同时包含读和写的 持有数(这些持有数即 占用的资源量,会在条件对象的wait方法调用时释放和 在tryAcquire方法中从新获取) ———— 这个有点难理解; 我认为是由于一个写锁不会阻塞同线程的读锁,同时由于写锁上能够建立条件,那么写锁释放,也就是执行 tryRelease的时候, 是应该把全部这些 写锁、读锁所有释放的~!xxx (这么多的that,这么多的定语、补语、状语,英语很差的人,直接懵逼) */ 尝试释放独占资源 protected final boolean tryRelease(int releases) { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); int nextc = getState() - releases; boolean free = exclusiveCount(nextc) == 0; 是否所有释放了 if (free) setExclusiveOwnerThread(null); 所有释放则同时把同步器全部者置为null setState(nextc); return free; } 尝试获取独占资源; 这个方法仅仅是基础实现; 可能被复写 protected final boolean tryAcquire(int acquires) { 独占模式 疑问,一个线程已经获取了写锁,那么它能够再次获取读锁吗? 答案,应该是true吧 /* * Walkthrough: * 1. If read count nonzero or write count nonzero * and owner is a different thread, fail. * 2. If count would saturate, fail. (This can only * happen if count is already nonzero.) * 3. Otherwise, this thread is eligible for lock if * it is either a reentrant acquire or * queue policy allows it. If so, update state * and set owner. 步骤: 1 若是读或写 锁的执行次数(调用次数)非0 并且 全部者 是其余线程,失败, 就是说此时不容许读也不容许写 2 若是 次数 立刻就要饱和(即次数太多了,即超过MAX_COUNT,state包含不下了), 失败(仅发生于次数已经非0) 3 不然,若是当前线程是可重入获取 队列策略容许,那么它就是 有资格获取到执行锁操做;而后还须要更新资源的状态和设置全部者 官方的说明感受很差理解,个人理解是: 若是策略(指公平策略)容许,或者没有被占用,或已经被本身独占过,那么就看看是否足够资源, 都知足就成功 */ Thread current = Thread.currentThread(); int c = getState(); int w = exclusiveCount(c); 独占的次数; 通常来讲,只能有一个线程独占吧;难道有 共享独占? if (c != 0) { 同步器已经有被占用 // (Note: if c != 0 and w == 0 then shared count != 0) if (w == 0 || current != getExclusiveOwnerThread()) 若是独占锁没有 或者刚恰好释放全部资源,且独占者非当前线程,返回false return false; if (w + exclusiveCount(acquires) > MAX_COUNT) 若是将要饱和,则抛异常 throw new Error("Maximum lock count exceeded"); // Reentrant acquire setState(c + acquires); 更新资源状态 return true; 成功返回 } // 执行到这里,代表还没被占用 if (writerShouldBlock() || 写是否应该阻塞, 对应非公平锁,不会阻塞;对应公平锁须要检查队列前面是否还有等待的线程 !compareAndSetState(c, c + acquires)) 或者不能 cas资源状态 成功; 成功则意味着没有竞争失败,也就是说 语义逻辑没有被其余线程的竞争破坏; 破坏了固然就应该失败 return false; 就返回false setExclusiveOwnerThread(current); return true; } 尝试释放共享资源 protected final boolean tryReleaseShared(int unused) { 这里的参数 这个方法没用到 Thread current = Thread.currentThread(); if (firstReader == current) { 若是最后一次读操做就是当前线程,那么就直接的释放 // assert firstReaderHoldCount > 0; if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; } else { 若是不是 HoldCounter rh = cachedHoldCounter; 获取缓存的读计数 if (rh == null || rh.tid != getThreadId(current)) 若是不是当前线程 rh = readHolds.get(); 就从线程变量中获取 int count = rh.count; if (count <= 1) { 若是读计数<= 1,那么就从线程变量中移除 readHolds.remove(); if (count <= 0) 不该该小于0 throw unmatchedUnlockException(); } --rh.count; 释放一个资源 } for (;;) { try操做应该是当即返回的,为何这里须要 自旋?由于 state是不断变化的,须要确保释放必定可以成功!! int c = getState(); int nextc = c - SHARED_UNIT; 为何要减去一个SHARED_UNIT? if (compareAndSetState(c, nextc)) 自旋,直到成功cas // Releasing the read lock has no effect on readers, // but it may allow waiting writers to proceed if // both read and write locks are now free. return nextc == 0; } } private IllegalMonitorStateException unmatchedUnlockException() { return new IllegalMonitorStateException( "attempt to unlock read lock, not locked by current thread"); } 独占读获取到资源的时候, 使用 compareAndSetState(c, c + acquires) 而共享读获取到资源的时候, 使用 compareAndSetState(c, c + SHARED_UNIT) ———— 为何这样作? 这是须要保证共享操做,发生在高位~! 逻辑上我须要共享计数增长1,可是实际操做的时候,咱们须要增长1+SHARED_UNIT,确保低位不会变;操做反应在高位, 对低位操做来讲1就是1,对于高位操做来讲1 就是 SHARED_UNIT, 必定要理解这一点!! ———— 释放的时候也是同样的作法; unused 参数如其名,是没有用到的,为何? 由于这个类中,每次只能获取、释放一个资源~!故方法内部其实使用了1 来替代参数; 那为何tryAcquire 方法不是如此?参照tryRelease方法,由于它们上面的条件队列 可能同时存在读计数、写计数~~!! protected final int tryAcquireShared(int unused) { 共享模式获取 /* * Walkthrough: * 1. If write lock held by another thread, fail. * 2. Otherwise, this thread is eligible for * lock wrt state, so ask if it should block * because of queue policy. If not, try * to grant by CASing state and updating count. * Note that step does not check for reentrant * acquires, which is postponed to full version * to avoid having to check hold count in * the more typical non-reentrant case. * 3. If step 2 fails either because thread * apparently not eligible or CAS fails or count * saturated, chain to version with full retry loop. 步骤: 1 若是写锁的全部者 是其余线程,失败, 就是说此时有写操做,再也不容许读操做 2 不然,若是当前线程 有资格锁定 写的部分资源,那么依据公平性检查是否应该阻塞; 若是没有资格,那么经过cas方式修改 注意: 当前方法不会检查可重入性;这种检查被延迟到了彻底版本 以免对更加典型的非可重入状况的检查(这样性能会牺牲比较大,得不偿失) 3 若是 由于 明显的不合适或者 立刻就要饱和,那么升级切换到 彻底版本 eligible 有资格 即readerShouldBlock返回true */ Thread current = Thread.currentThread(); int c = getState(); if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; int r = sharedCount(c); if (!readerShouldBlock() && 是否应该读阻塞; 若是应该读阻塞 意味着须要去排队,应该返回负数 r < MAX_COUNT && 没有饱和 compareAndSetState(c, c + SHARED_UNIT)) { 且cas成功 if (r == 0) { 第一个读 firstReader = current; firstReaderHoldCount = 1; } else if (firstReader == current) { firstReaderHoldCount++; 上次读线程 就是 本身 } else { HoldCounter rh = cachedHoldCounter; 获取缓存的读计数 if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); 从新设置 获取缓存的读计数 else if (rh.count == 0) readHolds.set(rh); // 这里不是很懂xxx rh.count++; 计数+1 } return 1; } return fullTryAcquireShared(current); 升级到 彻底版本 } /** * Full version of acquire for reads, that handles CAS misses 额外处理了cas失败、可重入读 * and reentrant reads not dealt with in tryAcquireShared. */ final int fullTryAcquireShared(Thread current) { /* * This code is in part redundant with that in * tryAcquireShared but is simpler overall by not * complicating tryAcquireShared with interactions between * retries and lazily reading hold counts. 这些代码和tryAcquireShared方法部分冗余了,可是整体而言更加简单了,由于它没有把tryAcquireShared和 在重试及延迟的读计数 之间的交互 搞得很复杂; */ HoldCounter rh = null; for (;;) { int c = getState(); if (exclusiveCount(c) != 0) { if (getExclusiveOwnerThread() != current) return -1; // else we hold the exclusive lock; blocking here // would cause deadlock. } else if (readerShouldBlock()) { // Make sure we're not acquiring read lock reentrantly if (firstReader == current) { 当前线程就是最后那个读线程, 那么确定是容许获取 // assert firstReaderHoldCount > 0; } else { if (rh == null) { rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) { rh = readHolds.get(); if (rh.count == 0) readHolds.remove(); } } if (rh.count == 0) return -1; 若是,, 那就阻止。 } } if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); if (compareAndSetState(c, c + SHARED_UNIT)) { 自旋+cas 会保证成功 if (sharedCount(c) == 0) { firstReader = current; firstReaderHoldCount = 1; } else if (firstReader == current) { firstReaderHoldCount++; } else { if (rh == null) rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); rh.count++; cachedHoldCounter = rh; // cache for release } return 1; } } } /** * Performs tryLock for write, enabling barging in both modes. * This is identical in effect to tryAcquire except for lack * of calls to writerShouldBlock. 准备执行写锁; 容许在两个模式下均可以闯入; 这个方法等效于 tryAcquire 除去 缺乏 writerShouldBlock 由于 它不须要问writerShouldBlock,就是true; */ final boolean tryWriteLock() { Thread current = Thread.currentThread(); int c = getState(); if (c != 0) { int w = exclusiveCount(c); if (w == 0 || current != getExclusiveOwnerThread()) return false; if (w == MAX_COUNT) throw new Error("Maximum lock count exceeded"); } 执行到这里,代表 c==0 或者 c != 0且w!=0 并且 当前线程正在独占 —— 代表要么是没有被占用,要么就是本身占用; 很是的“独断” if (!compareAndSetState(c, c + 1)) return false; setExclusiveOwnerThread(current); return true; } /** * Performs tryLock for read, enabling barging in both modes. * This is identical in effect to tryAcquireShared except for * lack of calls to readerShouldBlock. 准备执行读锁; 容许在两个模式下均可以闯入; 这个方法等效于 tryAcquireShared 除了 缺乏readerShouldBlock 由于 它不须要问readerShouldBlock,就是true; */ final boolean tryReadLock() { Thread current = Thread.currentThread(); for (;;) { int c = getState(); if (exclusiveCount(c) != 0 && 若是已经被独占 getExclusiveOwnerThread() != current) 而且独占者不是本身 return false; 返回失败 int r = sharedCount(c); 共享读的计数 if (r == MAX_COUNT) throw new Error("Maximum lock count exceeded"); 溢出 if (compareAndSetState(c, c + SHARED_UNIT)) { cas成功 if (r == 0) { 若是读计数为0,也就是说 尚未读锁 firstReader = current; firstReaderHoldCount = 1; } else if (firstReader == current) { firstReaderHoldCount++; } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); 找到当前线程对应的计数器 else if (rh.count == 0) readHolds.set(rh); rh.count++; 计数器++ } return true; } } } protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); 当前线程是否是独占全部者 } // Methods relayed to outer class final ConditionObject newCondition() { return new ConditionObject(); } final Thread getOwner() { // Must read state before owner to ensure memory consistency return ((exclusiveCount(getState()) == 0) ? null : getExclusiveOwnerThread()); } final int getReadLockCount() { return sharedCount(getState()); } final boolean isWriteLocked() { 为何没有getWriteLockCount 方法,由于不须要,isWriteLocked就足够 return exclusiveCount(getState()) != 0; WriteLock只有一个,也就是只有 存在不存在的区别 } final int getWriteHoldCount() { 能够认为是写锁 重入的次数 return isHeldExclusively() ? exclusiveCount(getState()) : 0; } final int getReadHoldCount() { if (getReadLockCount() == 0) return 0; Thread current = Thread.currentThread(); if (firstReader == current) return firstReaderHoldCount; 能够认为是 当前线程的读锁的重入的次数 HoldCounter rh = cachedHoldCounter; if (rh != null && rh.tid == getThreadId(current)) return rh.count; xxx int count = readHolds.get().count; if (count == 0) readHolds.remove(); 为何要删除,不删除也没用 return count; } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); readHolds = new ThreadLocalHoldCounter(); setState(0); // reset to unlocked state } final int getCount() { return getState(); } } /** * Nonfair version of Sync */ static final class NonfairSync extends Sync { private static final long serialVersionUID = -8159625535654395037L; final boolean writerShouldBlock() { return false; // writers can always barge 永远都不阻塞,说明写的优先级很高 } final boolean readerShouldBlock() { 复写Sync /* As a heuristic to avoid indefinite writer starvation, * block if the thread that momentarily appears to be head * of queue, if one exists, is a waiting writer. This is * only a probabilistic effect since a new reader will not * block if there is a waiting writer behind other enabled * readers that have not yet drained from the queue. 做为避免无限期的写线程饿死的启发式方法,若是瞬间出现的线程是队列的头,若是有一个线程是等待写线程的话,那就阻止。 这只是一个几率效应,由于若是在队列中尚未从队列中排出的其余已启用的读线程后面有一个等待的写线程,那么新的读线程就不会被阻止。 */ 对于非关系公平锁来讲,判断第一个入队的线程 是否是独占模式;—— 若是是独占的话,就不考虑公平不公平,直接不容许; 共享模式的话, 固然是容许的; 其实跟是否公平没多大 return apparentlyFirstQueuedIsExclusive(); } } /** * Fair version of Sync */ static final class FairSync extends Sync { private static final long serialVersionUID = -2274990926593161451L; final boolean writerShouldBlock() { 复写Sync的方法 return hasQueuedPredecessors(); 公平起见,须要判断是否有前任已经在等待;只要有线程在等待,那么无论它是读线程 仍是写线程, 都阻塞 } final boolean readerShouldBlock() { 复写Sync的方法 return hasQueuedPredecessors(); 公平起见,须要判断是否有前任已经在等待;只要有线程在等待,那么无论它是读线程 仍是写线程, 都阻塞 why? 由于 } } /** * The lock returned by method {@link ReentrantReadWriteLock#readLock}. */ 读锁 public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; private final Sync sync; /** * Constructor for use by subclasses 其实 并无观察到子类 * * @param lock the outer lock object 外部锁对象 * @throws NullPointerException if the lock is null */ protected ReadLock(ReentrantReadWriteLock lock) { sync = lock.sync; } /** * Acquires the read lock. 获取读锁 * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately. 若是写锁没有被其余线程占用,那么当即成功返回; * * <p>If the write lock is held by another thread then * the current thread becomes disabled for thread scheduling * purposes and lies dormant until the read lock has been acquired. 若是写锁没有被其余线程占用,那么阻塞, 直到获取成功; */ public void lock() { 不响应中断, 注意方法签名没有异常 sync.acquireShared(1); } /** * Acquires the read lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the read lock if the write lock is not held * by another thread and returns immediately. * * <p>If the write lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of two things happens: * * <ul> * * <li>The read lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * * </ul> * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the read lock, * * </ul> * * then {@link InterruptedException} is thrown and the current * thread's interrupted status is cleared. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to * the interrupt over normal or reentrant acquisition of the * lock. * * @throws InterruptedException if the current thread is interrupted */ 同上,可是 抛异常的方式 响应中断 , 注意方法签名 有中断异常 public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** * Acquires the read lock only if the write lock is not held by * another thread at the time of invocation. 若是写锁没有被其余线程占用,那么当即成功返回; * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately with the value * {@code true}. Even when this lock has been set to use a * fair ordering policy, a call to {@code tryLock()} * <em>will</em> immediately acquire the read lock if it is * available, whether or not other threads are currently * waiting for the read lock. This "barging" behavior * can be useful in certain circumstances, even though it * breaks fairness. If you want to honor the fairness setting * for this lock, then use {@link #tryLock(long, TimeUnit) * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent * (it also detects interruption). 若是写锁没有被其余线程占用,那么当即成功返回;read lock 不会阻塞read lock,它们能够共享; 可是若是read lock 被阻塞,说明存在write lock; 这个方法容许线程忽然的闯入,会破坏必定的公平性(可是若是要保证更好的公平,可使用tryLock(0, TimeUnit.SECONDS)) * * <p>If the write lock is held by another thread then * this method will return immediately with the value * {@code false}. 若是写锁被其余线程占用,那么当即失败返回 * * @return {@code true} if the read lock was acquired */ public boolean tryLock() { return sync.tryReadLock(); } /** * Acquires the read lock if the write lock is not held by * another thread within the given waiting time and the * current thread has not been {@linkplain Thread#interrupt * interrupted}. * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately with the value * {@code true}. If this lock has been set to use a fair * ordering policy then an available lock <em>will not</em> be * acquired if any other threads are waiting for the * lock. This is in contrast to the {@link #tryLock()} * method. If you want a timed {@code tryLock} that does * permit barging on a fair lock then combine the timed and * un-timed forms together: * * <pre> {@code * if (lock.tryLock() || * lock.tryLock(timeout, unit)) { * ... * }}</pre> * * <p>If the write lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * 大体同上,但同时响应中断和超时 */ public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 尝试锁定一个资源 } /** * Attempts to release this lock. * * <p>If the number of readers is now zero then the lock * is made available for write lock attempts. */ public void unlock() { sync.releaseShared(1); 释放一个资源; 若是读锁已经彻底释放了,那么写锁也是能够进入了 } /** * Throws {@code UnsupportedOperationException} because * {@code ReadLocks} do not support conditions. * * @throws UnsupportedOperationException always */ public Condition newCondition() { throw new UnsupportedOperationException(); 读锁不支持条件,why? 由于AQS的内部类Condition 只支持独占模式 } /** * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes the String {@code "Read locks ="} * followed by the number of held read locks. * * @return a string identifying this lock, as well as its lock state */ public String toString() { int r = sync.getReadLockCount(); return super.toString() + "[Read locks = " + r + "]"; } } /** * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. */ public static class WriteLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -4992448646407690164L; private final Sync sync; /** * Constructor for use by subclasses * * @param lock the outer lock object * @throws NullPointerException if the lock is null */ protected WriteLock(ReentrantReadWriteLock lock) { sync = lock.sync; } /** * Acquires the write lock. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately, setting the write lock hold count to * one. 若是写锁没有被其余线程 读或者写(其实就是全部状况),那么当即成功返回,随后写计数置为1; * * <p>If the current thread already holds the write lock then the * hold count is incremented by one and the method returns * immediately. 若是写锁已经被当前线程占有,那么当即成功返回,随后写计数 +1; * * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until the write lock has been acquired, at which * time the write lock hold count is set to one. 若是写锁已经被其余线程占有,那么陷入阻塞,直到成功获取 写锁; */ public void lock() { sync.acquire(1); 阻塞式获取一个资源 } /** * Acquires the write lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately, setting the write lock hold count to * one. * * <p>If the current thread already holds this lock then the * hold count is incremented by one and the method returns * immediately. * * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until one of two things happens: * 大体同上,但响应中断 public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } /** * Acquires the write lock only if it is not held by another thread * at the time of invocation. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately with the value {@code true}, * setting the write lock hold count to one. Even when this lock has * been set to use a fair ordering policy, a call to * {@code tryLock()} <em>will</em> immediately acquire the * lock if it is available, whether or not other threads are * currently waiting for the write lock. This "barging" * behavior can be useful in certain circumstances, even * though it breaks fairness. If you want to honor the * fairness setting for this lock, then use {@link * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * * <p>If the current thread already holds this lock then the * hold count is incremented by one and the method returns * {@code true}. * * <p>If the lock is held by another thread then this method * will return immediately with the value {@code false}. * * @return {@code true} if the lock was free and was acquired * by the current thread, or the write lock was already held * by the current thread; and {@code false} otherwise. */ 当即返回成功、或者失败, public boolean tryLock( ) { return sync.tryWriteLock(); 非阻塞式获取一个资源 } /** * Acquires the write lock if it is not held by another thread * within the given waiting time and the current thread has * not been {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately with the value {@code true}, * setting the write lock hold count to one. If this lock has been * set to use a fair ordering policy then an available lock * <em>will not</em> be acquired if any other threads are * waiting for the write lock. This is in contrast to the {@link * #tryLock()} method. If you want a timed {@code tryLock} * that does permit barging on a fair lock then combine the * timed and un-timed forms together: * * <pre> {@code * if (lock.tryLock() || * lock.tryLock(timeout, unit)) { * ... * }}</pre> * * <p>If the current thread already holds this lock then the * hold count is incremented by one and the method returns * {@code true}. * * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until one of three things happens: 大体同上,但同时响应中断和超时 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } /** * Attempts to release this lock. * * <p>If the current thread is the holder of this lock then * the hold count is decremented. If the hold count is now * zero then the lock is released. If the current thread is * not the holder of this lock then {@link * IllegalMonitorStateException} is thrown. * * @throws IllegalMonitorStateException if the current thread does not * hold this lock */ public void unlock() { sync.release(1); 释放一个资源; 若是 已经彻底释放了,那么至关于全部锁都已经释放 } /** * Returns a {@link Condition} instance for use with this * {@link Lock} instance. * <p>The returned {@link Condition} instance supports the same * usages as do the {@link Object} monitor methods ({@link * Object#wait() wait}, {@link Object#notify notify}, and {@link * Object#notifyAll notifyAll}) when used with the built-in * monitor lock. * * <ul> * * <li>If this write lock is not held when any {@link * Condition} method is called then an {@link * IllegalMonitorStateException} is thrown. (Read locks are * held independently of write locks, so are not checked or * affected. However it is essentially always an error to * invoke a condition waiting method when the current thread * has also acquired read locks, since other threads that * could unblock it will not be able to acquire the write * lock.) * * <li>When the condition {@linkplain Condition#await() waiting} * methods are called the write lock is released and, before * they return, the write lock is reacquired and the lock hold * count restored to what it was when the method was called. * * <li>If a thread is {@linkplain Thread#interrupt interrupted} while * waiting then the wait will terminate, an {@link * InterruptedException} will be thrown, and the thread's * interrupted status will be cleared. * * <li> Waiting threads are signalled in FIFO order. * * <li>The ordering of lock reacquisition for threads returning * from waiting methods is the same as for threads initially * acquiring the lock, which is in the default case not specified, * but for <em>fair</em> locks favors those threads that have been * waiting the longest. * * </ul> * * @return the Condition object */ public Condition newCondition() { return sync.newCondition(); } /** * Returns a string identifying this lock, as well as its lock * state. The state, in brackets includes either the String * {@code "Unlocked"} or the String {@code "Locked by"} * followed by the {@linkplain Thread#getName name} of the owning thread. * * @return a string identifying this lock, as well as its lock state */ public String toString() { Thread o = sync.getOwner(); return super.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]"); } /** * Queries if this write lock is held by the current thread. * Identical in effect to {@link * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. * * @return {@code true} if the current thread holds this lock and * {@code false} otherwise * @since 1.6 */ public boolean isHeldByCurrentThread() { 等效于ReentrantReadWriteLock.isWriteLockedByCurrentThread return sync.isHeldExclusively(); } /** * Queries the number of holds on this write lock by the current * thread. A thread has a hold on a lock for each lock action * that is not matched by an unlock action. Identical in effect * to {@link ReentrantReadWriteLock#getWriteHoldCount}. * * @return the number of holds on this lock by the current thread, * or zero if this lock is not held by the current thread * @since 1.6 */ public int getHoldCount() { return sync.getWriteHoldCount(); 等效于ReentrantReadWriteLock.getWriteHoldCount } } // Instrumentation and status /** * Returns {@code true} if this lock has fairness set true. * * @return {@code true} if this lock has fairness set true */ public final boolean isFair() { return sync instanceof FairSync; 是否公平 } /** * Returns the thread that currently owns the write lock, or * {@code null} if not owned. When this method is called by a * thread that is not the owner, the return value reflects a * best-effort approximation of current lock status. For example, * the owner may be momentarily {@code null} even if there are * threads trying to acquire the lock but have not yet done so. * This method is designed to facilitate construction of * subclasses that provide more extensive lock monitoring * facilities. * * @return the owner, or {@code null} if not owned */ protected Thread getOwner() { return sync.getOwner(); 返回最大努力的结果 } /** * Queries the number of read locks held for this lock. This * method is designed for use in monitoring system state, not for * synchronization control. * @return the number of read locks held */ 用于系统状态监控 public int getReadLockCount() { return sync.getReadLockCount(); } /** * Queries if the write lock is held by any thread. This method is * designed for use in monitoring system state, not for * synchronization control. 被设计用于系统状态监控,why?就是说只在系统状态相关函数中被调用 * * @return {@code true} if any thread holds the write lock and * {@code false} otherwise */ public boolean isWriteLocked() { return sync.isWriteLocked(); } /** * Queries if the write lock is held by the current thread. * * @return {@code true} if the current thread holds the write lock and * {@code false} otherwise */ public boolean isWriteLockedByCurrentThread() { return sync.isHeldExclusively(); } /** * Queries the number of reentrant write holds on this lock by the * current thread. A writer thread has a hold on a lock for * each lock action that is not matched by an unlock action. 查询写锁的重入次数,没有unlock以前,写线程在每次lock操做的时候增长一个计数, * * @return the number of holds on the write lock by the current thread, * or zero if the write lock is not held by the current thread */ public int getWriteHoldCount() { return sync.getWriteHoldCount(); } /** * Queries the number of reentrant read holds on this lock by the * current thread. A reader thread has a hold on a lock for * each lock action that is not matched by an unlock action. 查询读锁的重入次数 * * @return the number of holds on the read lock by the current thread, * or zero if the read lock is not held by the current thread * @since 1.6 */ public int getReadHoldCount() { return sync.getReadHoldCount(); } /** * Returns a collection containing threads that may be waiting to * acquire the write lock. Because the actual set of threads may * change dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive lock monitoring facilities. * * @return the collection of threads */ 获取队列中等待获取写锁的线程的集合,返回最大努力 protected Collection<Thread> getQueuedWriterThreads() { return sync.getExclusiveQueuedThreads(); } /** * Returns a collection containing threads that may be waiting to * acquire the read lock. Because the actual set of threads may * change dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive lock monitoring facilities. * * @return the collection of threads */ 获取队列中等待获取读锁的线程的集合,返回最大努力 protected Collection<Thread> getQueuedReaderThreads() { return sync.getSharedQueuedThreads(); } /** * Queries whether any threads are waiting to acquire the read or * write lock. Note that because cancellations may occur at any * time, a {@code true} return does not guarantee that any other ,返回最大努力 * thread will ever acquire a lock. This method is designed * primarily for use in monitoring of the system state. * * @return {@code true} if there may be other threads waiting to * acquire the lock */ 获取队列中是否有 等待获取的线程 public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** * Queries whether the given thread is waiting to acquire either * the read or write lock. Note that because cancellations may * occur at any time, a {@code true} return does not guarantee ,返回最大努力 * that this thread will ever acquire a lock. This method is * designed primarily for use in monitoring of the system state. * * @param thread the thread * @return {@code true} if the given thread is queued waiting for this lock * @throws NullPointerException if the thread is null */ 获取队列中是否有 等待获取的线程 public final boolean hasQueuedThread(Thread thread) { return sync.isQueued(thread); } /** * Returns an estimate of the number of threads waiting to acquire * either the read or write lock. The value is only an estimate ,返回最大努力 * because the number of threads may change dynamically while this * method traverses internal data structures. This method is * designed for use in monitoring of the system state, not for * synchronization control. * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** * Returns a collection containing threads that may be waiting to * acquire either the read or write lock. Because the actual set * of threads may change dynamically while constructing this * result, the returned collection is only a best-effort estimate. ,返回最大努力 * The elements of the returned collection are in no particular * order. This method is designed to facilitate construction of * subclasses that provide more extensive monitoring facilities. * * @return the collection of threads */ protected Collection<Thread> getQueuedThreads() { return sync.getQueuedThreads(); } /** * Queries whether any threads are waiting on the given condition * associated with the write lock. Note that because timeouts and * interrupts may occur at any time, a {@code true} return does * not guarantee that a future {@code signal} will awaken any ,返回最大努力 * threads. This method is designed primarily for use in * monitoring of the system state. * * @param condition the condition * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public boolean hasWaiters(Condition condition) { 返回写锁对象条件上的 等待者 if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); } /** * Returns an estimate of the number of threads waiting on the * given condition associated with the write lock. Note that because * timeouts and interrupts may occur at any time, the estimate * serves only as an upper bound on the actual number of waiters. ,返回最大努力 * This method is designed for use in monitoring of the system * state, not for synchronization control. * * @param condition the condition * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public int getWaitQueueLength(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); } /** * Returns a collection containing those threads that may be * waiting on the given condition associated with the write lock. * Because the actual set of threads may change dynamically while * constructing this result, the returned collection is only a ,返回最大努力 * best-effort estimate. The elements of the returned collection * are in no particular order. This method is designed to * facilitate construction of subclasses that provide more * extensive condition monitoring facilities. * * @param condition the condition * @return the collection of threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ protected Collection<Thread> getWaitingThreads(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); } /** * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes the String {@code "Write locks ="} * followed by the number of reentrantly held write locks, and the * String {@code "Read locks ="} followed by the number of held * read locks. * * @return a string identifying this lock, as well as its lock state */ public String toString() { int c = sync.getCount(); int w = Sync.exclusiveCount(c); int r = Sync.sharedCount(c); return super.toString() + "[Write locks = " + w + ", Read locks = " + r + "]"; } /** * Returns the thread id for the given thread. We must access * this directly rather than via method Thread.getId() because * getId() is not final, and has been known to be overridden in * ways that do not preserve unique mappings. */ static final long getThreadId(Thread thread) { return UNSAFE.getLongVolatile(thread, TID_OFFSET); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long TID_OFFSET; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> tk = Thread.class; TID_OFFSET = UNSAFE.objectFieldOffset (tk.getDeclaredField("tid")); } catch (Exception e) { throw new Error(e); } } }
这个类 仍是比较难理解的,主要在于可重入的理解,条件对象的支持,已经锁的降级与升级;ide