ReentrantLock,jdk源码阅读(二)

ReentrantLock:重入锁

使用:

public class ReentrantLockDemo {
    private static int count = 0;
    static Lock lock = new ReentrantLock();
    public static void inc(){
        lock.lock();
        try {
            Thread.sleep(1);
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0 ; i < 1000 ; i++){
            new Thread(()->ReentrantLockDemo.inc()).start();
        }
        Thread.sleep(4000);
        System.out.println(count);
    }
}

输出1000。

实现(设计思维):
需求:

  • 锁的互斥性怎么实现?需要一个共享资源实现互斥,进行标记0无锁,1有锁。大于1代表重入
  • 没有抢到锁的线程怎么办?释放cpu资源,等待被唤醒
  • 等待的线程怎么存储?等待队列
  • 公平锁和非公平锁?能否插队
  • 重入锁的特性?识别是否是一个人,用ThreadID

技术方案:

  • volatile state = 0(无锁),1有锁。大于1代表重入
  • wait/notify,可以唤醒等待线程,但是是随机的,无法唤醒指定的线程。所以选择LockSupport.park;unpark(thread) 这是unsafe类提供的方法。
  • 双向链表
  • 逻辑去实现
  • 在某个地方存储当前获得锁的线程id,用来判断下次来抢占的线程是不是同一个。

ReentrantLock源码(非公平锁为例)

  1. ReentrantLock中的lock方法。(非公平锁)
private final Sync sync;

public ReentrantLock() {
        sync = new NonfairSync();
    }
    

public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

public void lock() {
        sync.lock();
    }

sync是一个同步器是ReentrantLock中的静态内部类实现了AQS,Sync有两个业务实现,公平锁(FairSync)和非公平锁(NonfairSync),默认是非公平锁
类图:
在这里插入图片描述

  1. 进入非公平锁的lock方法
final void lock() {
//            抢占互斥资源
            if (compareAndSetState(0, 1)) //CAS原子操作比较并替换
//            抢占成功,存储抢到锁的线程,用来实现锁的重入
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }
  1. 抢占公共资源,即抢占锁
//   状态值(共享资源),用来标识锁,0无锁,1有锁,大于1重入锁
    private volatile int state;
//    expect预期值,update更新值
    protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
//        stateOffset是state变量的值在当前这个对象在内存中的偏移量,可以根据这个偏移量直接拿到state在内存中的值。
//        用stateOffset和expect比较,如果相等就更新成update,返回true
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
  1. 如果抢占成功,进入if,存储当前线程。然后lock方法结束
  2. 如果抢占失败,进入else。进入acquire(1);方法。
    acquire(int arg)方法中包含4个方法
public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
  1. tryAcquire(int acquires)(非公平)
//        继续尝试抢占锁
protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            //继续抢占
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    // 抢占成功,lock方法结束
                    return true;
                }
            }
            //线程重入
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                //线程重入成功,lock方法结束
                return true;
            }
            return false;
        }
  1. addWaiter(Node mode);将未获得锁的线程加入到队列
//    将未获得锁的线程加入到队列(双向链表)
private Node addWaiter(Node mode) {
//        构建当前线程的一个Node
        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;
            }
        }
        //初始化双向链表并把node节点加入队列
        enq(node);
        return node;
    }
private Node enq(final Node node) {
        //自旋
        for (;;) {
            Node t = tail;
//            尾节点=null
            if (t == null) { // Must initialize
//                初始化头部Node
                if (compareAndSetHead(new Node()))
//                    头节点,尾节点指向同一个节点Node
                    tail = head;
            } else {
//                当前节点的上一个节点指向尾节点
                node.prev = t;
//                更改尾部节点为当前节点
                if (compareAndSetTail(t, node)) {
//                    之前尾节点的下一个节点指向当前节点
                    t.next = node;
                    return t;
                }
            }
        }
    }
  1. acquireQueued(final Node node, int arg);去抢占锁或者阻塞
//    去抢占锁或者阻塞,node为没有获取到锁的线程的node
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
//            自旋
            for (;;) {
//                p为当前node的上一个node
                final Node p = node.predecessor();
//                如果是head节点的话,会去抢占一次锁
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
//                shouldParkAfterFailedAcquire(Node pred, Node node)抢占锁失败后是否要挂起,true挂起,false不挂起
//                parkAndCheckInterrupt()用来挂起
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
//    interrupted = true向上传递,让后续的代码知道线程中断过
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
//    抢占锁失败后是否要挂起,true挂起,false不挂起
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
//        SIGNAL允许被唤醒
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
//            CANCELLED>大于0
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
//            移除取消状态的线程节点
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
//            把waitStatus等待状态的值替换为SIGNAL
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }
    private final boolean  parkAndCheckInterrupt() {
//      挂起,这里挂起后除了unpark可以唤醒,阻塞的线程的interrupt()方法可以唤醒处于park状态下的线程
        LockSupport.park(this);
//      被唤醒后接着这里继续执行
//        获得当前中断标记,并复位
        return Thread.interrupted();
    }

-------------------------------------------------------------------------------------------------------

  1. ReentrantLock中的unlock方法。(非公平锁为例)
public void unlock() {
        sync.release(1);
    }
//    释放锁
    public final boolean release(int arg) {
//      tryRelease(arg)重入状态的话state-1,减到0就变成无锁,无锁返回true
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
//                unpark唤醒
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
  1. tryRelease(int releases)
//        重入状态的话State-1,减到0就变成无锁
        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }
  1. unparkSuccessor(Node node);
//    唤醒
    private void unparkSuccessor(Node node) {
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);
        Node s = node.next;
//        去除无效节点
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
//            唤醒
            LockSupport.unpark(s.thread);
    }
  1. 唤醒后接着在parkAndCheckInterrupt()中执行,然后接着自旋
   private final boolean parkAndCheckInterrupt() {
//      挂起,这里挂起后除了unpark可以唤醒,阻塞的线程的interrupt()方法可以唤醒处于park状态下的线程
        LockSupport.park(this);
//      被唤醒后接着这里继续执行
//      获得当前中断标记,并复位
        return Thread.interrupted();
    }
  1. interrupted = true向上传递,让后续的代码知道线程中断过
if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
//                    interrupted = true向上传递,让后续的代码知道线程中断过
                    interrupted = true;
  1. 重新抢占锁,抢占成功后执行这段逻辑
    在这里插入图片描述
  2. 进入acquire(int arg)方法中的最后一个方法
static void selfInterrupt() {
//     因为之前已经复位,再次中断,相当于把中断过程往下传递
        Thread.currentThread().interrupt();
    }

ReentrantLock源码(公平锁为例)

  1. ReentrantLock中的lock方法。(公平锁)
final void lock() {
            acquire(1);
        }
//        与非公平锁的区别,这里没有了抢占的步骤
final void lock() {
            acquire(1);
        }
  1. 进入acquire(int arg),与非公平锁还有一个区别在tryAcquire(int acquires)方法
public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
protected final boolean tryAcquire(int acquires) {
       final Thread current = Thread.currentThread();
       int c = getState();
       if (c == 0) {
//     判断队列里面是否有值,如果有值的话就不会去抢占
           if (!hasQueuedPredecessors() &&
                 compareAndSetState(0, acquires)) {
                 setExclusiveOwnerThread(current);
                 return true;
           }
       }
//     重入
       else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc < 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
       }
       return false;
    }

3.其他与非公平锁相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值