使用场景

读读不互斥,读写互斥

源码思路

state的数值,高16位是读锁标识,低16位是写锁标识
线程阻塞,就是放入aqs队列中。
读读不互斥,是如何实现的呢,
读写互斥,是如何实现的呢,

释放锁的时候

如果排队的紧更着2个都是读锁的话,都会被唤醒,体现读读不互斥的特性

  1. private void setHeadAndPropagate(Node node, int propagate) {
  2. Node h = head; // Record old head for check below
  3. setHead(node);
  4. /*
  5. * Try to signal next queued node if:
  6. * Propagation was indicated by caller,
  7. * or was recorded (as h.waitStatus either before
  8. * or after setHead) by a previous operation
  9. * (note: this uses sign-check of waitStatus because
  10. * PROPAGATE status may transition to SIGNAL.)
  11. * and
  12. * The next node is waiting in shared mode,
  13. * or we don't know, because it appears null
  14. *
  15. * The conservatism in both of these checks may cause
  16. * unnecessary wake-ups, but only when there are multiple
  17. * racing acquires/releases, so most need signals now or soon
  18. * anyway.
  19. */
  20. if (propagate > 0 || h == null || h.waitStatus < 0 ||
  21. (h = head) == null || h.waitStatus < 0) {
  22. Node s = node.next;
  23. if (s == null || s.isShared())
  24. //唤醒连着的读锁
  25. doReleaseShared();
  26. }
  27. }

读锁上锁

读读不互斥

  1. final boolean readerShouldBlock() {
  2. /* As a heuristic to avoid indefinite writer starvation,
  3. * block if the thread that momentarily appears to be head
  4. * of queue, if one exists, is a waiting writer. This is
  5. * only a probabilistic effect since a new reader will not
  6. * block if there is a waiting writer behind other enabled
  7. * readers that have not yet drained from the queue.
  8. */
  9. return apparentlyFirstQueuedIsExclusive();
  10. }