jdk源码解析七之Lock

淡淡的烟草味﹌ 2023-02-14 10:14 140阅读 0赞

文章目录

  • Lock
    • ReentrantLock
      • 构造
      • lock
      • unlock
      • tryLock
      • newCondition
      • 非公平策略获取锁
      • 总结
      • 非公平和公平获取锁的区别?
  • ReadWriteLock
    • ReentrantReadWriteLock
      • 构造
      • 获取读写锁
      • 读锁
        • lock
        • unlock
      • 写锁
        • lock
        • unlock
      • 锁降级
      • 总结
  • LockSupport
  • AbstractQueuedSynchronizer
  • Condition
    • newCondition
    • await
    • signal
    • signalAll
    • 总结
  • CAS例子

同步锁,是可重入锁,这样当访问本类或者超类其他加锁方法时,也能访问成功,从而避免死锁
加锁,可保证互斥,内存可见性,避免重排序

  1. 3种方式
  2. 1:减少锁持有时间
  3. H_AttributeStore/I_BetterAttributeStore
  4. 由于只有一个状态变量,可以使用其他容器类,如SyncMap/ConcurrentHashMap,这样无需显示同步,缩小了访问锁的范围,降低了代码维护风险
  5. 缩小同步代码块不能影响需要原子的操作
  6. 分解多个同步代码块时,可以将大量计算或阻塞操作从同步代码块中移除时,应该考虑
  7. 缩小锁范围
  8. 设置定时锁(Lock)
  9. F_CooperatingNoDeadlock:对一些方法公开调用,且缩小锁的使用粒度,极快释放,避免竞争.对一些耗时操作,copy一份副本,操作.
  10. 2:降低锁请求频率
  11. 减小锁粒度
  12. 可采用如下2方法,其本质是采用多个相互独立的锁来保护独立的状态变量
  13. 锁分解:J_ServerStatusBeforeSplit/K_ServerStatusAfterSplit
  14. 锁分段:L_StripedMap
  15. 场景:锁上的竞争频率>锁保护的数据上发生的竞争频率
  16. 3:使用带有协调机制的独占锁,这些机制允许更高的并发
  17. 放弃独占锁:使用并发容器,读写锁,不可变对象以及原子变量
  18. ReadWriteLock:多个读取以及单个写入的规则,读不需要加锁,写需要加锁
  19. 原子变量:降低热点域时的开销,如静态计数器,序列发生器,AtomicLong
  20. 或者非独占锁

等待锁的时间长,选择阻塞.否则自旋
公平:等待时间最长的获取锁
非公平:随机获取锁

  1. ABA问题
  2. 无法确保当前值没有发生变化,VA变成B,在由B变成A
  3. 可以使用AtomicStampedReference支持在2个变量上执行原子的条件更新,在引用上加版本号"避免ABA问题"
  4. AtomicMarkableReference:更新一个对象引用-布尔值二元组,通过二元组使节点保存在链表中同时又将其标记为"已删除的节点"

Lock

在这里插入图片描述
在这里插入图片描述

ReentrantLock

一个可重入的互斥锁 Lock
在这里插入图片描述

构造

  1. public ReentrantLock() {
  2. //默认初始化非公平的AQS
  3. sync = new NonfairSync();
  4. }
  5. public ReentrantLock(boolean fair) {
  6. //根据传入的值,选择公平还是非公平的策略
  7. sync = fair ? new FairSync() : new NonfairSync();
  8. }

lock

  1. public void lock() {
  2. //调用AQS
  3. sync.lock();
  4. }
  5. final void lock() {
  6. //更新state为1
  7. if (compareAndSetState(0, 1))
  8. //设置当前拥有独占访问权限的线程
  9. setExclusiveOwnerThread(Thread.currentThread());
  10. else
  11. //以独占模式获取对象,忽略中断。
  12. acquire(1);
  13. }
  14. public final void acquire(int arg) {
  15. if (//是否能成功加锁
  16. !tryAcquire(arg) &&
  17. //阻塞获取锁
  18. acquireQueued(
  19. //将当前线程以及独占模式等待标记,存储到尾端节点
  20. addWaiter(Node.EXCLUSIVE)
  21. , arg))
  22. //获取锁的过程中,当出现中断时,会执行到这里
  23. selfInterrupt();
  24. }
  25. protected final boolean tryAcquire(int acquires) {
  26. return nonfairTryAcquire(acquires);
  27. }
  28. final boolean nonfairTryAcquire(int acquires) {
  29. //获取当前线程
  30. final Thread current = Thread.currentThread();
  31. //获取同步状态的值
  32. int c = getState();
  33. //说明锁空闲
  34. if (c == 0) {
  35. //这个在tryLock调用
  36. if (compareAndSetState(0, acquires)) {
  37. setExclusiveOwnerThread(current);
  38. return true;
  39. }
  40. }
  41. else if (current == getExclusiveOwnerThread()) {
  42. //也就是这里支持重入锁
  43. //当前线程与当前拥有独占访问权限的线程一致
  44. //累加state
  45. int nextc = c + acquires;
  46. if (nextc < 0) // overflow
  47. throw new Error("Maximum lock count exceeded");
  48. setState(nextc);
  49. return true;
  50. }
  51. return false;
  52. }
  53. final boolean acquireQueued(final Node node, int arg) {
  54. boolean failed = true;
  55. try {
  56. boolean interrupted = false;
  57. for (;;) {
  58. //返回前端节点
  59. final Node p = node.predecessor();
  60. /*如果是当前头节点且再次获取锁成功
  61. */
  62. if (p == head && tryAcquire(arg)) {
  63. //设置头结点为当前节点,以及清空当前节点的pre和thread
  64. setHead(node);
  65. //释放GC
  66. p.next = null; // help GC
  67. //标记正常执行
  68. failed = false;
  69. return interrupted;
  70. }
  71. //检查并修改一个节点的状态,当该节点获取锁失败时。返回true如果线程需要阻塞。
  72. if (shouldParkAfterFailedAcquire(p, node) &&
  73. //这里执行阻塞
  74. parkAndCheckInterrupt())
  75. //标记已中断
  76. interrupted = true;
  77. }
  78. } finally {
  79. if (failed)
  80. cancelAcquire(node);
  81. }
  82. }

unlock

  1. public void unlock() {
  2. //释放锁
  3. sync.release(1);
  4. }
  5. public final boolean release(int arg) {
  6. if (//释放锁,成功则进入
  7. tryRelease(arg)) {
  8. //获取head
  9. Node h = head;
  10. //如果head不为空,且已经执行
  11. if (h != null && h.waitStatus != 0)
  12. //释放当前节点的下一个节点
  13. unparkSuccessor(h);
  14. return true;
  15. }
  16. //释放失败
  17. return false;
  18. }
  19. protected final boolean tryRelease(int releases) {
  20. //获取目前锁次数
  21. int c = getState() - releases;
  22. //如果当前线程不是当前拥有独占访问权限的线程,说明没有获取锁的情况下unlock,抛出异常
  23. if (Thread.currentThread() != getExclusiveOwnerThread())
  24. throw new IllegalMonitorStateException();
  25. boolean free = false;
  26. //正常释放锁
  27. if (c == 0) {
  28. free = true;
  29. //清空当前拥有独占锁的线程
  30. setExclusiveOwnerThread(null);
  31. }
  32. //设置锁次数
  33. setState(c);
  34. return free;
  35. }
  36. private void unparkSuccessor(Node node) {
  37. /*
  38. * If status is negative (i.e., possibly needing signal) try
  39. * to clear in anticipation of signalling. It is OK if this
  40. * fails or if status is changed by waiting thread.
  41. */
  42. int ws = node.waitStatus;
  43. //重置状态值
  44. if (ws < 0)
  45. compareAndSetWaitStatus(node, ws, 0);
  46. /*
  47. * Thread to unpark is held in successor, which is normally
  48. * just the next node. But if cancelled or apparently null,
  49. * traverse backwards from tail to find the actual
  50. * non-cancelled successor.
  51. */
  52. Node s = node.next;
  53. //如果下一个节点为null,且状态取消了,则从尾端遍历,查找未取消的线程
  54. //所以当看到next字段为null时并不意味着当前节点是队列的尾部了。
  55. //无论如何,如果一个next字段显示为null,我们能够从队列尾向前扫描进行复核。
  56. if (s == null || s.waitStatus > 0) {
  57. s = null;
  58. for (Node t = tail; t != null && t != node; t = t.prev)
  59. if (t.waitStatus <= 0)
  60. s = t;
  61. }
  62. if (s != null)
  63. LockSupport.unpark(s.thread);
  64. }

tryLock

  1. public boolean tryLock() {
  2. return sync.nonfairTryAcquire(1);
  3. }

newCondition

  1. public Condition newCondition() {
  2. return sync.newCondition();
  3. }

非公平策略获取锁

  1. final void lock() {
  2. //以独占模式获取对象,忽略中断。
  3. acquire(1);
  4. }
  5. protected final boolean tryAcquire(int acquires) {
  6. //获取当前线程
  7. final Thread current = Thread.currentThread();
  8. int c = getState();
  9. //锁空闲
  10. if (c == 0) {
  11. //判断当前线程是否等待线程队列中的第二个线程
  12. //如果是说明等待最久
  13. if (!hasQueuedPredecessors() &&
  14. compareAndSetState(0, acquires)) {
  15. //设置当前拥有独占访问权限的线程
  16. setExclusiveOwnerThread(current);
  17. return true;
  18. }
  19. }
  20. else if (current == getExclusiveOwnerThread()) {
  21. int nextc = c + acquires;
  22. if (nextc < 0)
  23. throw new Error("Maximum lock count exceeded");
  24. setState(nextc);
  25. return true;
  26. }
  27. return false;
  28. }
  29. public final boolean hasQueuedPredecessors() {
  30. // The correctness of this depends on head being initialized
  31. // before tail and on head.next being accurate if the current
  32. // thread is first in queue.
  33. Node t = tail; // Read fields in reverse initialization order
  34. Node h = head;
  35. Node s;
  36. //判断当前线程是否是等待线程节点的下一个线程
  37. return h != t &&
  38. ((s = h.next) == null || s.thread != Thread.currentThread());
  39. }

总结

独占锁,支持可重入,每次重入时state+1

非公平和公平获取锁的区别?

非公平获取锁的时候,不管怎么说,先去抢一波.抢不到再去抢一波,是在抢不到才会添加AQS队列等待.
在这里插入图片描述
在这里插入图片描述
而公平锁先判断是不是等待最长的线程,如果是则去抢,否则加入队列抢.
在这里插入图片描述

ReadWriteLock

在这里插入图片描述
分别维护2个锁,写锁是独占锁,读锁是共享锁,因为读的时间通常比写的时间长,所以写锁优先级比读锁高

ReentrantReadWriteLock

构造

  1. public ReentrantReadWriteLock() {
  2. //默认独占
  3. this(false);
  4. }
  5. public ReentrantReadWriteLock(boolean fair) {
  6. sync = fair ? new FairSync() : new NonfairSync();
  7. //静态内部类
  8. readerLock = new ReadLock(this);
  9. ///静态内部类
  10. writerLock = new WriteLock(this);
  11. }
  12. //高16读锁,低16写锁
  13. static final int SHARED_SHIFT = 16;
  14. static final int SHARED_UNIT = (1 << SHARED_SHIFT);
  15. static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
  16. static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
  17. /** Returns the number of shared holds represented in count */
  18. //返回共享个数
  19. static int sharedCount(int c) {
  20. return c >>> SHARED_SHIFT; }
  21. /** Returns the number of exclusive holds represented in count */
  22. //返回独占个数
  23. static int exclusiveCount(int c) {
  24. return c & EXCLUSIVE_MASK; }

获取读写锁

  1. public ReentrantReadWriteLock.WriteLock writeLock() {
  2. return writerLock; }
  3. public ReentrantReadWriteLock.ReadLock readLock() {
  4. return readerLock; }

读锁

lock

  1. public void lock() {
  2. sync.acquireShared(1);
  3. }
  4. protected final int tryAcquireShared(int unused) {
  5. /*
  6. * Walkthrough:
  7. * 1. If write lock held by another thread, fail.
  8. * 2. Otherwise, this thread is eligible for
  9. * lock wrt state, so ask if it should block
  10. * because of queue policy. If not, try
  11. * to grant by CASing state and updating count.
  12. * Note that step does not check for reentrant
  13. * acquires, which is postponed to full version
  14. * to avoid having to check hold count in
  15. * the more typical non-reentrant case.
  16. * 3. If step 2 fails either because thread
  17. * apparently not eligible or CAS fails or count
  18. * saturated, chain to version with full retry loop.
  19. */
  20. ///获取当前线程
  21. Thread current = Thread.currentThread();
  22. //获取当前锁的数量
  23. int c = getState();
  24. //持有写锁失败
  25. if (
  26. //获取独占锁数量!=0
  27. exclusiveCount(c) != 0 &&
  28. //且当前拥有独占访问权限的线程不等于当前线程,这里写锁可降级
  29. getExclusiveOwnerThread() != current)
  30. return -1;
  31. //获取共享锁数量
  32. int r = sharedCount(c);
  33. /*
  34. 第一次线程A读取,则记录第一个堵得线程以及个数
  35. 第二次线程A读取,则当前访问线程个数+1
  36. 第三次线程B读取,利用cachedHoldCounter缓存当前线程tid以及访问次数
  37. readHolds可以理解为一级缓存,绑定了每个线程的线程计数器
  38. cachedHoldCounter:二级缓存,缓存上一个线程执行重入锁的次数
  39. */
  40. if (//线程是否应该被阻塞
  41. !readerShouldBlock() &&
  42. //共享锁数量<最大锁数量
  43. r < MAX_COUNT &&
  44. //更新共享锁数量
  45. compareAndSetState(c, c + SHARED_UNIT)) {
  46. //如果是第一次读取
  47. if (r == 0) {
  48. //记录第一个读的线程
  49. firstReader = current;
  50. firstReaderHoldCount = 1;
  51. } else if (firstReader == current) {
  52. //如果当前访问的线程是第一个访问的线程,则访问线程数+1
  53. firstReaderHoldCount++;
  54. } else {
  55. //获取计数器
  56. HoldCounter rh = cachedHoldCounter;
  57. //计数器为null或者当前线程id不为正在运行线程id
  58. if (rh == null || rh.tid != getThreadId(current))
  59. //获取当前计数线程对应计数器
  60. cachedHoldCounter = rh = readHolds.get();
  61. else if (rh.count == 0)
  62. //设置线程计数器
  63. readHolds.set(rh);
  64. //线程重入次数+1
  65. rh.count++;
  66. }
  67. return 1;
  68. }
  69. //CAS尚未命中
  70. return fullTryAcquireShared(current);
  71. }
  72. final int fullTryAcquireShared(Thread current) {
  73. /*
  74. * This code is in part redundant with that in
  75. * tryAcquireShared but is simpler overall by not
  76. * complicating tryAcquireShared with interactions between
  77. * retries and lazily reading hold counts.
  78. */
  79. HoldCounter rh = null;
  80. for (;;) {
  81. int c = getState();
  82. //如果当前有独占锁,且独占线程非当前线程,则返回
  83. if (exclusiveCount(c) != 0) {
  84. if (getExclusiveOwnerThread() != current)
  85. return -1;
  86. // else we hold the exclusive lock; blocking here
  87. // would cause deadlock.
  88. } else if (readerShouldBlock()) {
  89. //写锁没有被获取,且读线程被阻塞
  90. // Make sure we're not acquiring read lock reentrantly
  91. //当前第一个线程为读线程,说明当前线程重入
  92. if (firstReader == current) {
  93. // assert firstReaderHoldCount > 0;
  94. } else {
  95. if (rh == null) {
  96. //获取缓存的计数器
  97. rh = cachedHoldCounter;
  98. //没有缓存计数器,或者计数器线程tid非当前线程tid(也就是说非上一个获取锁的线程)
  99. //对写锁的让步,如果第一个获取锁的线程是写锁,那么后续所有线程AQS排队
  100. if (rh == null || rh.tid != getThreadId(current)) {
  101. //获取线程计数器
  102. rh = readHolds.get();
  103. //重入锁数量为0
  104. if (rh.count == 0)
  105. //删除计数器
  106. readHolds.remove();
  107. }
  108. }
  109. //重入锁数量为0
  110. if (rh.count == 0)
  111. //AQS排队
  112. return -1;
  113. }
  114. }
  115. //读锁数量超过上限,异常
  116. if (sharedCount(c) == MAX_COUNT)
  117. throw new Error("Maximum lock count exceeded");
  118. //设置读锁数量
  119. //当前线程是第一个获取读锁的线程,或是上一个执行任务的线程会执行到这里
  120. //也就是说重入获取读锁的线程才会执行到这里
  121. if (compareAndSetState(c, c + SHARED_UNIT)) {
  122. //
  123. if (sharedCount(c) == 0) {
  124. firstReader = current;
  125. firstReaderHoldCount = 1;
  126. } else if (firstReader == current) {
  127. firstReaderHoldCount++;
  128. } else {
  129. if (rh == null)
  130. rh = cachedHoldCounter;
  131. if (rh == null || rh.tid != getThreadId(current))
  132. rh = readHolds.get();
  133. else if (rh.count == 0)
  134. readHolds.set(rh);
  135. //重入数量累加
  136. rh.count++;
  137. //缓存计数器
  138. cachedHoldCounter = rh; // cache for release
  139. }
  140. return 1;
  141. }
  142. }
  143. }
  144. final boolean readerShouldBlock() {
  145. //下一个锁是否是独占锁
  146. return apparentlyFirstQueuedIsExclusive();
  147. }
  148. final boolean apparentlyFirstQueuedIsExclusive() {
  149. Node h, s;
  150. return (h = head) != null &&
  151. (s = h.next) != null &&
  152. !s.isShared() &&
  153. s.thread != null;
  154. }

unlock

  1. protected final boolean tryReleaseShared(int unused) {
  2. //获取当前线程
  3. Thread current = Thread.currentThread();
  4. //当前线程为第一个获取读锁的线程
  5. if (firstReader == current) {
  6. // assert firstReaderHoldCount > 0;
  7. //如果是最后一次释放锁,则直接置空firstReader
  8. if (firstReaderHoldCount == 1)
  9. firstReader = null;
  10. else
  11. //头锁重入次数-1
  12. firstReaderHoldCount--;
  13. } else {
  14. //获取上一个获取读锁的线程计数器
  15. HoldCounter rh = cachedHoldCounter;
  16. if (rh == null || rh.tid != getThreadId(current))
  17. //非上一次执行的线程,则获取当前线程计数器
  18. rh = readHolds.get();
  19. int count = rh.count;
  20. if (count <= 1) {
  21. //删除当前线程计数器
  22. readHolds.remove();
  23. //说明没有之前获取锁,直接释放则异常
  24. if (count <= 0)
  25. throw unmatchedUnlockException();
  26. }
  27. //线程重入次数-1
  28. --rh.count;
  29. }
  30. for (;;) {
  31. int c = getState();
  32. int nextc = c - SHARED_UNIT;
  33. if (compareAndSetState(c, nextc))
  34. // Releasing the read lock has no effect on readers,
  35. // but it may allow waiting writers to proceed if
  36. // both read and write locks are now free.
  37. //锁为0说明正确释放
  38. return nextc == 0;
  39. }
  40. }

写锁

lock

  1. protected final boolean tryAcquire(int acquires) {
  2. //获取当前线程
  3. Thread current = Thread.currentThread();
  4. ///获取当前线程状态
  5. int c = getState();
  6. //获取独占锁重入数量
  7. int w = exclusiveCount(c);
  8. //如果有线程获取读写锁
  9. if (c != 0) {
  10. // (Note: if c != 0 and w == 0 then shared count != 0)
  11. //写锁没被占用,或当前拥有独占访问权限的线程不等于当前线程,说明有读锁被占用,返回false
  12. if (w == 0 || current != getExclusiveOwnerThread())
  13. return false;
  14. //读写锁数量超过最大数量,异常
  15. if (w + exclusiveCount(acquires) > MAX_COUNT)
  16. throw new Error("Maximum lock count exceeded");
  17. // Reentrant acquire
  18. //执行到这里,说明写锁被重入
  19. setState(c + acquires);
  20. return true;
  21. }
  22. //执行到这里说明没有读写锁占用
  23. if (
  24. //写锁是否阻塞
  25. writerShouldBlock() ||
  26. //修改状态
  27. !compareAndSetState(c, c + acquires))
  28. //如果写锁没有被阻塞,且修改状态失败,则返回false
  29. return false;
  30. //设置锁被当前线程独占
  31. setExclusiveOwnerThread(current);
  32. return true;
  33. }

非公平获取锁是否阻塞

  1. final boolean writerShouldBlock() {
  2. return false; // writers can always barge
  3. }

公平获取锁是否阻塞

  1. final boolean writerShouldBlock() {
  2. return hasQueuedPredecessors();
  3. }
  4. public final boolean hasQueuedPredecessors() {
  5. // The correctness of this depends on head being initialized
  6. // before tail and on head.next being accurate if the current
  7. // thread is first in queue.
  8. Node t = tail; // Read fields in reverse initialization order
  9. Node h = head;
  10. Node s;
  11. //判断当前线程是否是等待线程节点的下一个线程
  12. return h != t &&
  13. ((s = h.next) == null || s.thread != Thread.currentThread());
  14. }

unlock

  1. protected final boolean tryRelease(int releases) {
  2. //拥有独占锁的不是当前线程,则异常
  3. if (!isHeldExclusively())
  4. throw new IllegalMonitorStateException();
  5. int nextc = getState() - releases;
  6. boolean free = exclusiveCount(nextc) == 0;
  7. //独占锁数量为0,则清空锁的持有者
  8. if (free)
  9. setExclusiveOwnerThread(null);
  10. //设置锁数量
  11. setState(nextc);
  12. return free;
  13. }

锁降级

在这里插入图片描述

  1. * class CachedData {
  2. * Object data;
  3. * volatile boolean cacheValid;
  4. * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  5. *
  6. * void processCachedData() {
  7. * rwl.readLock().lock();
  8. * if (!cacheValid) {
  9. * // Must release read lock before acquiring write lock
  10. * rwl.readLock().unlock();
  11. * rwl.writeLock().lock();
  12. * try {
  13. * // Recheck state because another thread might have
  14. * // acquired write lock and changed state before we did.
  15. * if (!cacheValid) {
  16. * data = ...
  17. * cacheValid = true;
  18. * }
  19. * // Downgrade by acquiring read lock before releasing write lock
  20. * rwl.readLock().lock();
  21. * } finally {
  22. * rwl.writeLock().unlock(); // Unlock write, still hold read
  23. * }
  24. * }
  25. *
  26. * try {
  27. * use(data);
  28. * } finally {
  29. * rwl.readLock().unlock();
  30. * }
  31. * }
  32. * }}

总结

当获取写锁的情况下,当前线程依旧能获取读锁,这称之为锁降级
当获取读锁情况下,不能获取写锁
这里始终保证了写锁>读锁等级.
避免了锁等级一样,出现获取锁的乱序问题.

读锁添加的State是SHARED_UNIT的倍数

这里分别用firstReader记录第一个获取读锁的线程
cachedHoldCounter获取上一个获取读锁的线程计数器
readHolds记录每个线程锁对应的计数器

如果下一个锁是独占锁,且非公平模式下,则后续所有线程都进入AQS等待锁,只有已经获取读锁的依旧可以执行

  1. final boolean readerShouldBlock() {
  2. //下一个锁是否是独占锁
  3. return apparentlyFirstQueuedIsExclusive();
  4. }
  5. protected final int tryAcquireShared(int unused) {
  6. /
  7. if (//线程是否应该被阻塞
  8. !readerShouldBlock() &&{
  9. //...
  10. }
  11. //CAS尚未命中
  12. return fullTryAcquireShared(current);
  13. }
  14. final int fullTryAcquireShared(Thread current) {
  15. HoldCounter rh = null;
  16. for (;;) {
  17. int c = getState();
  18. //如果当前有独占锁,且独占线程非当前线程,则返回
  19. if (exclusiveCount(c) != 0) {
  20. if (getExclusiveOwnerThread() != current)
  21. return -1;
  22. /
  23. } else if (readerShouldBlock()) {
  24. /
  25. }
  26. //读锁数量超过上限,异常
  27. if (sharedCount(c) == MAX_COUNT)
  28. throw new Error("Maximum lock count exceeded");
  29. //设置读锁数量
  30. //当前线程是第一个获取读锁的线程,或是上一个执行任务的线程会执行到这里
  31. //也就是说重入获取读锁的线程才会执行到这里
  32. if (compareAndSetState(c, c + SHARED_UNIT)) {
  33. //
  34. if (sharedCount(c) == 0) {
  35. firstReader = current;
  36. firstReaderHoldCount = 1;
  37. } else if (firstReader == current) {
  38. firstReaderHoldCount++;
  39. } else {
  40. if (rh == null)
  41. rh = cachedHoldCounter;
  42. if (rh == null || rh.tid != getThreadId(current))
  43. rh = readHolds.get();
  44. else if (rh.count == 0)
  45. readHolds.set(rh);
  46. //重入数量累加
  47. rh.count++;
  48. //缓存计数器
  49. cachedHoldCounter = rh; // cache for release
  50. }
  51. return 1;
  52. }
  53. }
  54. }

在这里插入图片描述
公平模式下直接让下一个线程获取锁

  1. final boolean readerShouldBlock() {
  2. return hasQueuedPredecessors();
  3. }
  4. public final boolean hasQueuedPredecessors() {
  5. // The correctness of this depends on head being initialized
  6. // before tail and on head.next being accurate if the current
  7. // thread is first in queue.
  8. Node t = tail; // Read fields in reverse initialization order
  9. Node h = head;
  10. Node s;
  11. return h != t &&
  12. ((s = h.next) == null || s.thread != Thread.currentThread());
  13. }

LockSupport

park:为了线程调度,禁用当前线程,除非许可可用。
unpark:如果给定线程的许可尚不可用,则使其可用。

  1. class FIFOMutex {
  2. private final AtomicBoolean locked = new AtomicBoolean(false);
  3. private final Queue<Thread> waiters
  4. = new ConcurrentLinkedQueue<Thread>();
  5. public void lock() {
  6. boolean wasInterrupted = false;
  7. Thread current = Thread.currentThread();
  8. waiters.add(current);
  9. // Block while not first in queue or cannot acquire lock
  10. while (waiters.peek() != current ||
  11. !locked.compareAndSet(false, true)) {
  12. LockSupport.park(this);
  13. if (Thread.interrupted()) // ignore interrupts while waiting
  14. wasInterrupted = true;
  15. }
  16. waiters.remove();
  17. if (wasInterrupted) // reassert interrupt status on exit
  18. current.interrupt();
  19. }
  20. public void unlock() {
  21. locked.set(false);
  22. LockSupport.unpark(waiters.peek());
  23. }
  24. }

AbstractQueuedSynchronizer

  1. public abstract class AbstractQueuedSynchronizer
  2. extends AbstractOwnableSynchronizer
  3. implements java.io.Serializable {
  4. private static final long serialVersionUID = 7373984972572414691L;
  5. static final class Node {
  6. /** Marker to indicate a node is waiting in shared mode */
  7. static final Node SHARED = new Node();
  8. /** Marker to indicate a node is waiting in exclusive mode */
  9. static final Node EXCLUSIVE = null;
  10. /** waitStatus value to indicate thread has cancelled */
  11. //这个节点由于超时或中断被取消了。节点不会离开(改变)这个状态。尤其,一个被取消的线程不再会被阻塞了
  12. static final int CANCELLED = 1;
  13. /** waitStatus value to indicate successor's thread needs unparking */
  14. /* 这个节点的后继(或者即将被阻塞)被阻塞(通过park阻塞)了,所以当前节点需要唤醒它的后继当它被释放或者取消时。
  15. 为了避免竞争,获取方法必须首先表示他们需要一个通知信号,然后再原子性的尝试获取锁,如果失败,则阻塞。
  16. 也就是说,在获取锁的操作中,需要确保当前node的preNode的waitStatus状态值为’SIGNAL’,才可以被阻塞,当
  17. 获取锁失败时。(『shouldParkAfterFailedAcquire』方法的用意就是这)*/
  18. static final int SIGNAL = -1;
  19. /** waitStatus value to indicate thread is waiting on condition */
  20. /* 这个节点当前在一个条件队列中。它将不会被用于当做一个同步队列的节点直到它被转移到同步队列中,
  21. 转移的同时状态值(waitStatus)将会被设置为0。
  22. (这里使用这个值将不会做任何事情与该字段其他值对比,只是为了简化机制)。*/
  23. static final int CONDITION = -2;
  24. //一个releaseShared操作必须被广播给其他节点。(只有头节点的)该值会在doReleaseShared方法中被设置去确保持续的广播,即便其他操作的介入。
  25. static final int PROPAGATE = -3;
  26. }
  27. private Node enq(final Node node) {
  28. //(自旋+CAS)
  29. for (;;) {
  30. Node t = tail;
  31. //初始化,头和尾为空节点
  32. if (t == null) {
  33. // Must initialize
  34. if (compareAndSetHead(new Node()))
  35. tail = head;
  36. } else {
  37. ///设置尾部节点
  38. node.prev = t;
  39. if (compareAndSetTail(t, node)) {
  40. //这里可能出现next=null短暂现象.
  41. t.next = node;
  42. return t;
  43. }
  44. }
  45. }
  46. }
  47. private Node addWaiter(Node mode) {
  48. //包装当前线程以及表示该节点正在共享或独占模式下等待
  49. Node node = new Node(Thread.currentThread(), mode);
  50. // Try the fast path of enq; backup to full enq on failure
  51. Node pred = tail;
  52. if (pred != null) {
  53. //将当前节点添加到尾部节点
  54. node.prev = pred;
  55. if (compareAndSetTail(pred, node)) {
  56. pred.next = node;
  57. return node;
  58. }
  59. }
  60. enq(node);
  61. return node;
  62. }
  63. private void unparkSuccessor(Node node) {
  64. int ws = node.waitStatus;
  65. //重置状态值
  66. if (ws < 0)
  67. compareAndSetWaitStatus(node, ws, 0);
  68. Node s = node.next;
  69. //如果下一个节点为null,且状态取消了,则从尾端遍历,查找未取消的线程
  70. //所以当看到next字段为null时并不意味着当前节点是队列的尾部了。
  71. //无论如何,如果一个next字段显示为null,我们能够从队列尾向前扫描进行复核。
  72. if (s == null || s.waitStatus > 0) {
  73. s = null;
  74. for (Node t = tail; t != null && t != node; t = t.prev)
  75. if (t.waitStatus <= 0)
  76. s = t;
  77. }
  78. if (s != null)
  79. LockSupport.unpark(s.thread);
  80. }
  81. private void doReleaseShared() {
  82. //广播释放所有阻塞的锁
  83. for (;;) {
  84. Node h = head;
  85. if (h != null && h != tail) {
  86. int ws = h.waitStatus;
  87. //更新默认值0,且解除park
  88. if (ws == Node.SIGNAL) {
  89. if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
  90. continue; // loop to recheck cases
  91. unparkSuccessor(h);
  92. }
  93. else if (ws == 0 &&
  94. !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
  95. continue; // loop on failed CAS
  96. }
  97. if (h == head) // loop if head changed
  98. break;
  99. }
  100. }
  101. private void setHeadAndPropagate(Node node, int propagate) {
  102. Node h = head; // Record old head for check below
  103. //设置当前节点为头节点,以及清空当前线程和前置节点
  104. setHead(node);
  105. //如果闭锁是开的,且头为null,且waitStatus
  106. //如果标识了广播(propagate>0),
  107. if (propagate > 0 || h == null || h.waitStatus < 0 ||
  108. (h = head) == null || h.waitStatus < 0) {
  109. Node s = node.next;
  110. //如果当前节点为null或者当前节点为共享等待标记,则释放,执行
  111. //enq初始化时,会有短暂为null现象
  112. if (s == null || s.isShared())
  113. doReleaseShared();
  114. }
  115. }
  116. private void cancelAcquire(Node node) {
  117. // Ignore if node doesn't exist
  118. if (node == null)
  119. return;
  120. node.thread = null;
  121. // Skip cancelled predecessors
  122. //将node的prev属性指向一个在它之前的有效的节点
  123. Node pred = node.prev;
  124. while (pred.waitStatus > 0)
  125. node.prev = pred = pred.prev;
  126. // predNext is the apparent node to unsplice. CASes below will
  127. // fail if not, in which case, we lost race vs another cancel
  128. // or signal, so no further action is necessary.
  129. /* 这个predNext是pred表面上的下一个连接的节点(即,无需考虑该节点是否被取消了)。
  130. 下面的CAS操作将会失败(『compareAndSetNext(pred, predNext, null);』or『compareAndSetNext(pred, predNext, next);』)
  131. ,如果和其他的取消或通知操作发生竞争时,这时不需要进一步的操作。因为如果产生竞争,
  132. 说明pred的next已经被修改了,并且是最新的值了,而我们的操作也就没有要执行的必要了。*/
  133. Node predNext = pred.next;
  134. // Can use unconditional write instead of CAS here.
  135. // After this atomic step, other Nodes can skip past us.
  136. // Before, we are free of interference from other threads.
  137. /* 将node的waitStatus设置为’CANCELLED’。这里可以使用无条件的写代替CAS(注意,node的waitStatus是volatile的)。
  138. 在这个原子操作之后,其他节点会跳过我们(即,跳过waitStatus被置位CANCELLED的节点),
  139. 在这个原子操作之前,我们不受其他线程的干扰。也就是说,无论其他线程对node的waitStatus是否有在操作,
  140. 在当前的情况下我们都需要将这个node的waitStatus置为’CANCELLED’。*/
  141. node.waitStatus = Node.CANCELLED;
  142. // If we are the tail, remove ourselves.
  143. /* 如果待取消的node节点是队列尾节点的话(即,『node == tail』),那么删除node自己即可。使用CAS将tail节点设置成前面得到的第一个有效前驱节点
  144. (即,『compareAndSetTail(node, pred)』)。并且CAS操作成功的话,
  145. 执行『compareAndSetNext(pred, predNext, null);』
  146. 也就是将tail的next置为null的意思。如果该CAS操作失败的话,
  147. 没关系。说明此时tail已经被修改了。*/
  148. if (node == tail && compareAndSetTail(node, pred)) {
  149. compareAndSetNext(pred, predNext, null);
  150. } else {
  151. // If successor needs signal, try to set pred's next-link
  152. // so it will get one. Otherwise wake it up to propagate.
  153. int ws;
  154. if (
  155. //pred不是head节点
  156. pred != head &&
  157. //pred.waitStatus为SIGNAL” 或者
  158. ((ws = pred.waitStatus) == Node.SIGNAL ||
  159. //“pred.waitStatus <= 0”时且通过CAS将pred.waitStatus设置为SIGNAL”成功
  160. (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
  161. //pred的thread非空
  162. pred.thread != null) {
  163. Node next = node.next;
  164. /* 当node的next节点非空,且next节点的waitStatus<=0(说明next节点未被取消)时,
  165. 通过CAS将pred的next执行node的next(即,pred.next = node.next)。
  166. 同时,如果该CAS操作失败是没关系的,说明有其他线程操作已经修改了该pre的next值。*/
  167. if (next != null && next.waitStatus <= 0)
  168. compareAndSetNext(pred, predNext, next);
  169. } else {
  170. //释放当前这个待取消节点的下一个节点。
  171. //当prev是head节点,或者prev也被取消的话,会执行『unparkSuccessor(node);』来释放node的下一个节点,其实也就是pred的下一个节点)
  172. unparkSuccessor(node);
  173. }
  174. //释放GC
  175. node.next = node; // help GC
  176. }
  177. }
  178. private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
  179. int ws = pred.waitStatus;
  180. //则说明node的前驱节点已经被要求去通知释放它的后继节点,所以node可以安全的被挂起(park)
  181. if (ws == Node.SIGNAL)
  182. /*
  183. * This node has already set status asking a release
  184. * to signal it, so it can safely park.
  185. */
  186. return true;
  187. if (ws > 0) {
  188. //则说明node的前驱节点被取消了。那么跳过这个前驱节点并重新标志一个有效的前驱节点(即,
  189. // waitStatus <= 0 的节点可作为有效的前驱节点),然后,退出方法,返回false。
  190. /*
  191. * Predecessor was cancelled. Skip over predecessors and
  192. * indicate retry.
  193. */
  194. do {
  195. node.prev = pred = pred.prev;
  196. } while (pred.waitStatus > 0);
  197. pred.next = node;
  198. } else {
  199. //其他情况下,即pred.waitStatus为’0’或’PROPAGATE’。
  200. // 表示我们需要一个通知信号(即,当前的node需要唤醒的通知),
  201. // 但是当前还不能挂起node。
  202. // 调用『compareAndSetWaitStatus(pred, ws, Node.SIGNAL)』方法通过CAS的方式来修改前驱节点的waitStatus为“SIGNAL”。
  203. // 退出方法,返回false。
  204. /*
  205. * waitStatus must be 0 or PROPAGATE. Indicate that we
  206. * need a signal, but don't park yet. Caller will need to
  207. * retry to make sure it cannot acquire before parking.
  208. */
  209. //等待状态值指示后续线程需要断开连接
  210. compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
  211. }
  212. return false;
  213. }
  214. private final boolean parkAndCheckInterrupt() {
  215. //为了线程调度,在许可可用之前禁用当前线程。
  216. LockSupport.park(this);
  217. //测试当前线程是否已经中断。
  218. return Thread.interrupted();
  219. }
  220. final boolean acquireQueued(final Node node, int arg) {
  221. boolean failed = true;
  222. try {
  223. boolean interrupted = false;
  224. for (;;) {
  225. //返回前端节点
  226. final Node p = node.predecessor();
  227. /*如果是当前头节点且再次获取锁成功
  228. */
  229. if (p == head && tryAcquire(arg)) {
  230. //设置头结点为当前节点,以及清空当前节点的pre和thread
  231. setHead(node);
  232. //释放GC
  233. p.next = null; // help GC
  234. //标记正常执行
  235. failed = false;
  236. return interrupted;
  237. }
  238. //检查并修改一个节点的状态,当该节点获取锁失败时。返回true如果线程需要阻塞。
  239. if (shouldParkAfterFailedAcquire(p, node) &&
  240. //这里执行阻塞
  241. parkAndCheckInterrupt())
  242. //标记已中断
  243. interrupted = true;
  244. }
  245. } finally {
  246. if (failed)
  247. cancelAcquire(node);
  248. }
  249. }
  250. /**
  251. * Acquires in shared interruptible mode.
  252. * @param arg the acquire argument
  253. */
  254. private void doAcquireSharedInterruptibly(int arg)
  255. throws InterruptedException {
  256. //将当前线程以及共享模式等待标记,存储到尾端节点
  257. final Node node = addWaiter(Node.SHARED);
  258. //标记是否正常处理,如果出现中断,则取消执行
  259. boolean failed = true;
  260. try {
  261. for (;;) {
  262. //返回前端节点
  263. final Node p = node.predecessor();
  264. //如果是当前头节点
  265. /*
  266. 经过发现,只有head节点,执行完后,才会执行下一个节点
  267. */
  268. if (p == head) {
  269. //判断闭锁是否是开的
  270. int r = tryAcquireShared(arg);
  271. //如果闭锁是开的
  272. if (r >= 0) {
  273. //设置node为head,以及清空node的pre和thread
  274. setHeadAndPropagate(node, r);
  275. //释放GC
  276. p.next = null; // help GC
  277. //标记正确执行
  278. failed = false;
  279. return;
  280. }
  281. }
  282. //检查并修改一个节点的状态,当该节点获取锁失败时。返回true如果线程需要阻塞。
  283. if (shouldParkAfterFailedAcquire(p, node) &&
  284. //这里执行阻塞
  285. parkAndCheckInterrupt())
  286. throw new InterruptedException();
  287. }
  288. } finally {
  289. if (failed)
  290. cancelAcquire(node);
  291. }
  292. }
  293. public final void acquire(int arg) {
  294. if (//是否能成功加锁
  295. !tryAcquire(arg) &&
  296. //阻塞获取锁
  297. acquireQueued(
  298. //将当前线程以及独占模式等待标记,存储到尾端节点
  299. addWaiter(Node.EXCLUSIVE)
  300. , arg))
  301. //获取锁的过程中,当出现中断时,会执行到这里
  302. selfInterrupt();
  303. }
  304. public final boolean release(int arg) {
  305. if (//释放锁,成功则进入
  306. tryRelease(arg)) {
  307. //获取head
  308. Node h = head;
  309. //如果head不为空,且已经执行
  310. if (h != null && h.waitStatus != 0)
  311. //释放当前节点的下一个节点
  312. unparkSuccessor(h);
  313. return true;
  314. }
  315. //释放失败
  316. return false;
  317. }
  318. public final void acquireShared(int arg) {
  319. //共享模式获取锁,忽略中断
  320. if (tryAcquireShared(arg) < 0)
  321. doAcquireShared(arg);
  322. }
  323. public final void acquireSharedInterruptibly(int arg)
  324. throws InterruptedException {
  325. //中断检测
  326. if (Thread.interrupted())
  327. throw new InterruptedException();
  328. //个数是否消耗完,消耗完则直接跳过,直接执行
  329. //否则执行下列方法
  330. if (tryAcquireShared(arg) < 0)
  331. doAcquireSharedInterruptibly(arg);
  332. }
  333. public final boolean releaseShared(int arg) {
  334. //检测闭锁是否开启
  335. if (tryReleaseShared(arg)) {
  336. //释放
  337. doReleaseShared();
  338. return true;
  339. }
  340. return false;
  341. }
  342. public final boolean hasQueuedPredecessors() {
  343. Node t = tail; // Read fields in reverse initialization order
  344. Node h = head;
  345. Node s;
  346. //判断当前线程是否是等待线程节点的下一个线程
  347. return h != t &&
  348. ((s = h.next) == null || s.thread != Thread.currentThread());
  349. }
  350. }

Condition

在这里插入图片描述

主要看java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject

newCondition

  1. public Condition newCondition() {
  2. return sync.newCondition();
  3. }
  4. final ConditionObject newCondition() {
  5. return new ConditionObject();
  6. }

await

  1. public final void await() throws InterruptedException {
  2. //中断处理
  3. if (Thread.interrupted())
  4. throw new InterruptedException();
  5. //添加下一个节点到等待队列
  6. Node node = addConditionWaiter();
  7. //阻塞时候,会释放锁
  8. int savedState = fullyRelease(node);
  9. //1) 当在被通知前被中断则将中断模式设置为THROW_IE;
  10. // 2) 当在被通知后则将中断模式设置为REINTERRUPT(因为acquireQueued不会响应中断)。
  11. int interruptMode = 0;
  12. //如果不在同步队列,则阻塞
  13. while (!isOnSyncQueue(node)) {
  14. //阻塞当前线程
  15. //在另一个线程调用sign和unlock之后唤醒
  16. //调用sign,将当前等待线程添加到同步线程
  17. //然后调用unlock释放同步线程
  18. LockSupport.park(this);
  19. //如果中断,确保节点添加到同步队列,并跳出循环
  20. if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  21. break;
  22. }
  23. //阻塞竞争锁,如果被通知或者中断的话.获取锁的话会重新计入重入次数
  24. if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  25. interruptMode = REINTERRUPT;
  26. if (node.nextWaiter != null) // clean up if cancelled
  27. //删除状态不为CONDITION的节点
  28. unlinkCancelledWaiters();
  29. //根据中断模式抛出异常
  30. if (interruptMode != 0)
  31. reportInterruptAfterWait(interruptMode);
  32. }
  33. private Node addConditionWaiter() {
  34. //获取上一个等待节点
  35. Node t = lastWaiter;
  36. // If lastWaiter is cancelled, clean out.
  37. if (t != null && t.waitStatus != Node.CONDITION) {
  38. unlinkCancelledWaiters();
  39. t = lastWaiter;
  40. }
  41. //创建一个新的节点,并标记CONDITION
  42. Node node = new Node(Thread.currentThread(), Node.CONDITION);
  43. //如果上一个等待节点为空,则设置为第一个节点
  44. if (t == null)
  45. firstWaiter = node;
  46. else
  47. //否则设置为下一个节点
  48. t.nextWaiter = node;
  49. lastWaiter = node;
  50. return node;
  51. }
  52. final int fullyRelease(Node node) {
  53. boolean failed = true;
  54. try {
  55. int savedState = getState();
  56. //释放所有锁?
  57. if (release(savedState)) {
  58. failed = false;
  59. //返回保存状态
  60. return savedState;
  61. } else {
  62. throw new IllegalMonitorStateException();
  63. }
  64. } finally {
  65. //失败,则标记状态为取消
  66. if (failed)
  67. node.waitStatus = Node.CANCELLED;
  68. }
  69. }
  70. final boolean isOnSyncQueue(Node node) {
  71. //如果节点在条件队列或者节点前置为null,则阻塞
  72. //prev为null的时候,说明是头节点,而头结点一般是空node,所以不可能是头结点
  73. //name也就是处于transferForSignal方法中compareAndSetWaitStatus和enq之间的中间状态
  74. if (node.waitStatus == Node.CONDITION || node.prev == null)
  75. return false;
  76. //如果有后续任务,说明被其他线程修改,已经入队
  77. if (node.next != null) // If has successor, it must be on queue
  78. return true;
  79. /*
  80. * node.prev can be non-null, but not yet on queue because
  81. * the CAS to place it on queue can fail. So we have to
  82. * traverse from tail to make sure it actually made it. It
  83. * will always be near the tail in calls to this method, and
  84. * unless the CAS failed (which is unlikely), it will be
  85. * there, so we hardly ever traverse much.
  86. */
  87. //状态不是CONDITION,且前置节点不为null,后置节点为null,可能是尾节点,则从后查找
  88. //从后到前查找是否有node,如果没有说明还正在添加则阻塞
  89. //也就是enq调用compareAndSetTail存在并发修改失败
  90. return findNodeFromTail(node);
  91. }
  92. //尾部查找node节点
  93. private boolean findNodeFromTail(Node node) {
  94. Node t = tail;
  95. for (;;) {
  96. if (t == node)
  97. return true;
  98. if (t == null)
  99. return false;
  100. t = t.prev;
  101. }
  102. }
  103. private int checkInterruptWhileWaiting(Node node) {
  104. /*
  105. 没有异常,返回0
  106. 中断在通知之前,THROW_IE
  107. 中断在通知之后,REINTERRUPT
  108. */
  109. return Thread.interrupted() ?
  110. (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
  111. 0;
  112. }
  113. final boolean transferAfterCancelledWait(Node node) {
  114. //当前节点状态为CONDITION,中断在通知之前
  115. //设置状态为0,将取消的线程添加到同步队列中
  116. if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
  117. enq(node);
  118. return true;
  119. }
  120. /*
  121. * If we lost out to a signal(), then we can't proceed
  122. * until it finishes its enq(). Cancelling during an
  123. * incomplete transfer is both rare and transient, so just
  124. * spin.
  125. */
  126. /*
  127. 节点不是CONDITION状态,这说明中断在通知之后
  128. 自旋添加到队列中
  129. */
  130. while (!isOnSyncQueue(node))
  131. Thread.yield();
  132. //线程在通知之后被取消
  133. return false;
  134. }
  135. final boolean acquireQueued(final Node node, int arg) {
  136. boolean failed = true;
  137. try {
  138. boolean interrupted = false;
  139. for (;;) {
  140. //返回前端节点
  141. final Node p = node.predecessor();
  142. /*如果是当前头节点且再次获取锁成功
  143. */
  144. if (p == head && tryAcquire(arg)) {
  145. //设置头结点为当前节点,以及清空当前节点的pre和thread
  146. setHead(node);
  147. //释放GC
  148. p.next = null; // help GC
  149. //标记正常执行
  150. failed = false;
  151. return interrupted;
  152. }
  153. //检查并修改一个节点的状态,当该节点获取锁失败时。返回true如果线程需要阻塞。
  154. if (shouldParkAfterFailedAcquire(p, node) &&
  155. //这里执行阻塞
  156. parkAndCheckInterrupt())
  157. //标记已中断
  158. interrupted = true;
  159. }
  160. } finally {
  161. if (failed)
  162. cancelAcquire(node);
  163. }
  164. }
  165. private void unlinkCancelledWaiters() {
  166. //删除状态不为CONDITION的节点
  167. //trail ->t->next
  168. Node t = firstWaiter;
  169. //记录上一个状态为CONDITION的节点
  170. Node trail = null;
  171. while (t != null) {
  172. Node next = t.nextWaiter;
  173. if (t.waitStatus != Node.CONDITION) {
  174. t.nextWaiter = null;
  175. if (trail == null)
  176. firstWaiter = next;
  177. else
  178. //删除t节点
  179. trail.nextWaiter = next;
  180. if (next == null)
  181. lastWaiter = trail;
  182. }
  183. else
  184. trail = t;
  185. t = next;
  186. }
  187. }
  188. private void reportInterruptAfterWait(int interruptMode)
  189. throws InterruptedException {
  190. //抛出中断异常
  191. if (interruptMode == THROW_IE)
  192. throw new InterruptedException();
  193. else if (interruptMode == REINTERRUPT)
  194. //中断
  195. selfInterrupt();
  196. }

signal

  1. public final void signal() {
  2. //发送信号的是否是当前线程,如果不是则异常
  3. //确保signal在lock之后,且同一个线程
  4. if (!isHeldExclusively())
  5. throw new IllegalMonitorStateException();
  6. //获取第一个等待节点
  7. Node first = firstWaiter;
  8. if (first != null)
  9. //发送信号
  10. doSignal(first);
  11. }
  12. private void doSignal(Node first) {
  13. do {
  14. //删除first节点,并设置firstWaiter为下一个节点
  15. //如果下一个节点为null,则清空lastWaiter
  16. if ( (firstWaiter = first.nextWaiter) == null)
  17. lastWaiter = null;
  18. //清空first下一个节点
  19. first.nextWaiter = null;
  20. } while (
  21. //将删除的first节点添加到同步队列
  22. //如果添加失败,说明已经有其他线程添加成功了
  23. //却白first不为null,再次遍历
  24. !transferForSignal(first) &&
  25. (first = firstWaiter) != null);
  26. }
  27. final boolean transferForSignal(Node node) {
  28. /*
  29. * If cannot change waitStatus, the node has been cancelled.
  30. */
  31. //修改状态为普通状态,如果失败,说明其他线程正在执行添加操作
  32. if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
  33. return false;
  34. /*
  35. * Splice onto queue and try to set waitStatus of predecessor to
  36. * indicate that thread is (probably) waiting. If cancelled or
  37. * attempt to set waitStatus fails, wake up to resync (in which
  38. * case the waitStatus can be transiently and harmlessly wrong).
  39. */
  40. //node添加到同步队列最后,且返回上一个节点
  41. Node p = enq(node);
  42. //获取入队前前置节点状态
  43. int ws = p.waitStatus;
  44. //前置节点为取消状态的时候,也就是说他不会在被唤醒,如果当前线程执行unlock执行unpark操作的时候,唤醒的是一个取消节点
  45. //而这不是我们愿意看到的,我们希望唤醒的是一个正常节点,这里提前唤醒下一个正常节点线程.在正常节点被唤醒后,会竞争锁,竞争锁成功后,会删除取消的节点
  46. //前置节点为取消状态,直接唤醒
  47. //或者为非取消状态则修改为SIGNAL,如果失败则唤醒
  48. if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
  49. //唤醒当前线程
  50. LockSupport.unpark(node.thread);
  51. //添加同步队列成功
  52. return true;
  53. }

signalAll

  1. public final void signalAll() {
  2. //非当前获取独占锁线程异常
  3. if (!isHeldExclusively())
  4. throw new IllegalMonitorStateException();
  5. //获取第一个等待节点
  6. Node first = firstWaiter;
  7. if (first != null)
  8. //遍历添加所有等待节点到同步队列
  9. doSignalAll(first);
  10. }
  11. private void doSignalAll(Node first) {
  12. lastWaiter = firstWaiter = null;
  13. do {
  14. Node next = first.nextWaiter;
  15. first.nextWaiter = null;
  16. transferForSignal(first);
  17. first = next;
  18. } while (first != null);
  19. }

总结

await时,会释放锁
在这里插入图片描述

await有2个阻塞状态,第一个阻塞状态等待当前节点添加到同步队列
第二个阻塞状态是竞争锁.
在这里插入图片描述
ConditionObject维护了2个节点,当await时将节点添加到等待队列中
当signal时,将队列节点添加到同步队列head和tail中.在执行unlock的时候被唤醒.
但是在signal
时,如果上一个节点出现取消状态或者上一个同步队列节点修改状态失败,则提前唤醒当前节点
在这里插入图片描述
在这里插入图片描述
对CAS中间状态的维护
在这里插入图片描述
在这里插入图片描述

CAS例子

  1. package concurrent.D;
  2. import java.util.concurrent.atomic.AtomicReference;
  3. /**
  4. * LinkedQueue
  5. * <p/>
  6. * Insertion in the Michael-Scott nonblocking queue algorithm
  7. 线程安全
  8. * Michael-Scott非阻塞链接队列算法中的插入算法
  9. *
  10. * ConcurrentLinkedQueue使用原子域更新器AtomicReferenceFieldUpdater来代替AtomicReference,从而提升性能
  11. * @author Brian Goetz and Tim Peierls
  12. */
  13. public class M_LinkedQueue <E> {
  14. private static class Node <E> {
  15. final E item;
  16. final AtomicReference<Node<E>> next;
  17. public Node(E item, Node<E> next) {
  18. this.item = item;
  19. this.next = new AtomicReference<Node<E>>(next);
  20. }
  21. }
  22. private final Node<E> dummy = new Node<E>(null, null);
  23. private final AtomicReference<Node<E>> head
  24. = new AtomicReference<Node<E>>(dummy);
  25. private final AtomicReference<Node<E>> tail
  26. = new AtomicReference<Node<E>>(dummy);
  27. public boolean put(E item) {
  28. Node<E> newNode = new Node<E>(item, null);
  29. while (true) {
  30. Node<E> curTail = tail.get();
  31. Node<E> tailNext = curTail.next.get();
  32. if (curTail == tail.get()) {
  33. //检测状态是否处于C-D之间
  34. if (tailNext != null) {
  35. // Queue in intermediate state, advance tail
  36. //队列处于中间状态,推进尾节点,处于状态C-D之间,curTail.next是有值得
  37. tail.compareAndSet(curTail, tailNext);
  38. } else {
  39. // In quiescent state, try inserting new node
  40. //处于稳定状态,尝试插入新节点到列表队尾
  41. if (curTail.next.compareAndSet(null, newNode)) {
  42. //状态C
  43. // Insertion succeeded, try advancing tail
  44. //插入操作成功,尝试推进尾节点,推入失败也没事,其他线程会帮忙推送
  45. tail.compareAndSet(curTail, newNode); //状态D
  46. //因为其他线程帮忙推送又或者自己推送成功,保证了幂等性,所以直接返回即可
  47. return true;
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }

发表评论

表情:
评论列表 (有 0 条评论,140人围观)

还没有评论,来说两句吧...

相关阅读