jdkReentrantLock&&源码分析

    科技2025-05-23  42

    创建一个公平或者非公平的锁

    非公平锁

    static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; final void lock() { //CAS修改状态 if (compareAndSetState(0, 1)) //修改成功将当前持有锁线程修改为当前线程 setExclusiveOwnerThread(Thread.currentThread()); else //加入队列 acquire(1); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } }

    acquire

    如果tryAcquire()获取失败,则要执行addWaiter()向等待队列中添加一个独占模式的节点。

    public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }

    acquireQueued

    final boolean acquireQueued(final Node node, int arg) { boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { //设置头节点为当前线程 setHead(node); //把之前的头结点设置为null p.next = null; // help GC failed = false; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && //加锁失败阻塞 parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } }

    tryAcquire

    尝试加锁

    final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //如果线程状态为0 cas成1 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } //如果状态不是0判断是否是当前线程 else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }

    addWaiter

    这个方法的注释:创建一个入队node为当前线程,Node.EXCLUSIVE 是独占锁, Node.SHARED 是共享锁。 先找到等待队列的tail节点pred,如果pred!=null,就把当前线程添加到pred后面进入等待队列,如果不存在tail节点执行enq()

    private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; if (pred != null) { //新节点指向上一个节点 node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; }

    enq

    这里进行了循环,如果此时存在了tail就执行同上一步骤的添加队尾操作,如果依然不存在,就把当前线程作为head结点。 插入节点后,调用acquireQueued()进行阻塞

    private Node enq(final Node node) { for (;;) { Node t = tail; //判断头节点是不是null if (t == null) { // Must initialize //CAS设置头节点后再进入循环 if (compareAndSetHead(new Node())) //初始化时头尾节点为同一个 tail = head; } else { //新入队的节点上一个等于头节点 node.prev = t; //cas尾节点 if (compareAndSetTail(t, node)) { //上一个节点的下一个 t.next = node; return t; } } } }
    Processed: 0.010, SQL: 8