javacurrency锁的实现

读写锁(ReentrantReadWriteLock)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protected final boolean (int acquires) {
Thread current = Thread.currentThread();
int c = getState();
int w = exclusiveCount(c);
if (c != 0) {
//如果c!=0 && w!=0 ,那么肯定不存在读锁,只需判断当前写锁是否是当前线程即可
if (w == 0 || current != getExclusiveOwnerThread())
return false;
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
//上述判断全部通过,肯定是重入锁
setState(c + acquires);
return true;
}
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;
setExclusiveOwnerThread(current);
return true;
}

ConcurrentLinkedQueue

  1. 入队
    1
    2
    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
    public boolean offer(E e) {
    checkNotNull(e);
    final Node<E> newNode = new Node<E>(e);
    for (Node<E> t = tail, p = t;;) {
    Node<E> q = p.next;
    if (q == null) {
    // p是尾节点
    if (p.casNext(null, newNode)) {
    // Successful CAS is the linearization point
    // for e to become an element of this queue,
    // and for newNode to become "live".
    if (p != t) // hop two nodes at a time
    casTail(t, newNode); // Failure is OK.
    return true;
    }
    // Lost CAS race to another thread; re-read next
    }
    else if (p == q)
    // We have fallen off list. If tail is unchanged, it
    // will also be off-list, in which case we need to
    // jump to head, from which all live nodes are always
    // reachable. Else the new tail is a better bet.
    p = (t != (t = tail)) ? t : head;
    else
    // Check for tail updates after two hops.
    p = (p != t && t != (t = tail)) ? t : q;
    }
    }