• 源码解析之——ReentrantLock


    ReentrantLock的使用

    Lock lock = new ReentrantLock();
    lock.lock();
    try {
     doSomething();
    }finally {
     lock.unlock();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    lock.lock () 就是在显式的上锁。上锁后,下面的代码块一定要放到 try 中,并且要结合 finally 代码块调用 lock.unlock () 来释放锁,否则一定 doSomething 方法中出现任何异常,这个锁将永远不会被释放掉。

    ReentrantLock支持公平和非公平锁两种形式,在声明的时候传入true,则为公平锁。

    上面Lock.lock的方式获取的锁,是一种阻塞的方式加锁,即直到获取锁才会继续向下进行。
    还有一种tryLock的方法获取锁,这个方法有两个重载,第一个是无参的tryLock方法,被调用后,该方法会立即返回获取锁的情况。获取为 true,未能获取为 false。第二个是有参数的 tryLock 方法,通过传入时间和单位,来控制等待获取锁的时长。如果超过时间未能获取锁则放回 false,反之返回 true。

    源码分析

    1、lock方法

    public void lock() {
        //ReentrantLock通过内置的sync对象加锁
            sync.lock();
    }
    
    • 1
    • 2
    • 3
    • 4

    sync对象在renentrantlock的构造函数中已经给赋值,即赋值为公平的sync和非公平的 sync

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

    在这里插入图片描述
    再来看NonfairSync和fairSync中的lock方法实现:

    公平锁

    
            final void lock() {
                acquire(1);
            }
    
    • 1
    • 2
    • 3
    • 4

    方法最后会执行一个acquire(1);方法去尝试获取锁。acquire方法处于独占模式,通过调用tryAcquire来实现,成功后返回,否则将会被放入到队列中,反复尝试获取锁,直到tryAcquire成功。

    public final void acquire(int arg) {
            if (!tryAcquire(arg) &&
                acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
                selfInterrupt();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    /**
             * Fair version of tryAcquire.  Don't grant access unless
             * recursive call or no waiters or is first.
             */
            protected final boolean tryAcquire(int acquires) {
                // 拿到当前线程
                final Thread current = Thread.currentThread();
                // 获取AQS中锁的状态
                int c = getState();
                // 如果锁目前是自由状态
                if (c == 0) {
                    // 因为是公平锁,所以hasQueuedPredecessors()会先判断队列中是否有其他线程早于当前线程等待
                    if (!hasQueuedPredecessors() &&
                        compareAndSetState(0, acquires)) {//执行cas操作,将aqs中state的状态 改为1(非自由状态)
                        // 设置当前线程为独占访问的线程
                        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;
            }
    
    • 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 final boolean hasQueuedPredecessors() {
            // The correctness of this depends on head being initialized
            // before tail and on head.next being accurate if the current
            // thread is first in queue.
            Node t = tail; // Read fields in reverse initialization order
            Node h = head;
            Node s;
            return h != t &&
                ((s = h.next) == null || s.thread != Thread.currentThread());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
     // 如果当前状态值等于预期值,则自动将同步状态设置为给定的更新值。该操作具有{@code volatile}读写的内存语义。
    protected final boolean compareAndSetState(int expect, int update) {
            // See below for intrinsics setup to support this
            // 拿到aqs中state的值,与期望值进行比较,如果相等,执行更新操作
            return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    // 设置当前线程为独占访问的线程   
    protected final void setExclusiveOwnerThread(Thread thread) {
            exclusiveOwnerThread = thread;
        }
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述
    如果在tryAcquire方法中返回true,说明当前线程已经获得锁,并且是独占状态,直接返回继续执行同步代码,如果返回false,说明当前锁已经被其他线程持有,将会尝试执行addWaiter下面的方法,将当前线程封装一个等待node,加入到队列中进行排队,然后调用acquireQueued 尝试排队获取锁:

    /**
         * Creates and enqueues node for current thread and given mode.
         *
         * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
         * @return the new node
         */
    //将当前线程封装成一个节点,放入队列中
        private Node addWaiter(Node mode) {
            Node node = new Node(Thread.currentThread(), mode);
            // Try the fast path of enq; backup to full enq on failure
            //将队尾复制给pred
            Node pred = tail;
            // 判断pred是否为空(判断队尾是否有节点),if语句成立说明队列已经初始化了,已经有线程在排队了
            if (pred != null) {
                // 如果队尾有节点,将当前节点的头指针指向队尾节点
                node.prev = pred;
                // //这里需要cas,因为防止多个线程加锁,确保nc入队的时候是原子操作
                if (compareAndSetTail(pred, node)) {
                    // 把pred的下一个节点设置为当前节点,这个nc自己成为对尾了
                    pred.next = node;
                    return node;
                }
            }
            // if不成立说明队列还没有初始化,此时还没有线程在排队,则初始化队列,将当前线程作为尾结点放入队列中
            enq(node);
            return node;
        }
    
    • 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
    /**
         * Inserts node into queue, initializing if necessary. See picture above.
         * @param node the node to insert
         * @return node's predecessor
         */
        private Node enq(final Node node) {
            for (;;) {
                Node t = tail;
                if (t == null) { // Must initialize 必须初始化
                    if (compareAndSetHead(new Node()))
                        tail = head;
                } else {
                    node.prev = t;
                    if (compareAndSetTail(t, node)) {
                        t.next = node;
                        return t;
                    }
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    //队列中的线程不断查看自己的排队情况
    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);
                    // 将当前节点的上一个 节点移除队列
                    p.next = null; // help GC
                    // 获取锁成功
                    failed = false;
                    // 返回没有被中断
                    return interrupted;
                }
                // 如果上一个节点不是头结点,或者上一个节点还没有处理完没有释放锁,那么就将上一个节点的状态改成park状态也就是-1状态。(每个节点都有一个状态,默认为0,表示无状态,-1标识在park。为了防止变动,节点要先变成park状态后才能将标识改成-1,但是如果节点已经是park状态了,就完全释放CPU资源了,不能执行任何代码,所以需要他的后一个节点将前一个节点改成-1状态)
                if (shouldParkAfterFailedAcquire(p, node) && //改上一个节点的状态成功之后;自己park;
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
    • 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
    • 30
    • 31
    • 32

    整个获取锁的过程我们可以总结下:

    1. 直接通过 tryAcquire 尝试获取锁,成功直接返回;
    2. 如果没能获取成功,那么把自己加入等待队列;
    3. 自旋查看自己的排队情况;
    4. 如果排队轮到自己,那么尝试通过 tryAcquire 获取锁;
    5. 如果没轮到自己,那么回到第三步查看自己的排队情况。

    非公平锁

    对于非公平锁,在执行lock方法时,会立即尝试获得锁,失败时才备份到正常的获取

    /**
         * Sync object for non-fair locks
         */
        static final class NonfairSync extends Sync {
            private static final long serialVersionUID = 7316153563782823691L;
    
            /**
             * Performs lock.  Try immediate barge, backing up to normal
             * acquire on failure.
             */
            final void lock() {
                // 首先就会尝试去获得锁,获得成功后将当前线程变为独占模式
                if (compareAndSetState(0, 1))
                    setExclusiveOwnerThread(Thread.currentThread());
                else
                    acquire(1);
            }
    
            // 非公平锁的 tryAcquire方法实现与公平锁是不一样的,如下
            protected final boolean tryAcquire(int acquires) {
                return nonfairTryAcquire(acquires);
            }
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    /**
             * Performs non-fair tryLock.  tryAcquire is implemented in
             * subclasses, but both need nonfair try for trylock method.
             */
            final boolean nonfairTryAcquire(int acquires) {
                final Thread current = Thread.currentThread();
                int c = getState();
                if (c == 0) {
                    if (compareAndSetState(0, acquires)) {
                        setExclusiveOwnerThread(current);
                        return true;
                    }
                }
                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;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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

    2、unLock方法

    public void unlock() {
        sync.release(1);
    }
    
    • 1
    • 2
    • 3
     public final boolean release(int arg) {
         // 如果当前锁状态为0,即释放锁成功,那么则会通过 unparkSuccessor 方法找到队列中第一个 waitStatus<0 的线程进行唤醒
            if (tryRelease(arg)) {
                Node h = head;
                // 如果头结点不为空,并且初始化条件不为0,尝试唤醒头结点的后继节点
                if (h != null && h.waitStatus != 0)
                    // 尝试唤醒头结点的后继节点
                    unparkSuccessor(h);
                return true;
            }
            return false;
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    protected final boolean tryRelease(int releases) {
        		// 释放锁的时候需要对原来的锁状态进行减一操作,直到减为0的时候,返回当前锁的状态为0(自由状态)
                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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    总结:

    ReentrantLock 的设计思想是通过 FIFO 的队列保存等待锁的线程。通过 volatile 类型的 state 保存锁的持有数量,从而实现了锁的可重入性。而公平锁则是通过判断自己是否排队成功,来决定是否去争抢锁。

    ReentrantLock与Synchronized的区别

    1、实现的机制不同,synchronized是JVM级别的关键字,而ReenTrantLock是类级别的。
    2、ReentrantLock是非常灵活的,能够选择什么时候获得锁什么时候释放锁。但是Synchronized锁的获得和释放是被动的,只有当同步代码块执行结束或者出现异常的时候才会释放锁。
    3、ReentrantLock可以判断锁的状态。
    4、对于ReentrantLock来说有公平锁和非公平锁之说,但是Synchronized是一个非公平锁。

  • 相关阅读:
    SRM采购管理系统投标管理模块:阳光招采,助力建筑材料企业智慧采购
    Linux服务器后台运行python项目 + Linux命令行下终止当前程序
    PyCharm运行bash脚本
    在MySQL中创建新的数据库,可以使用命令,也可以通过MySQL工作台
    mysql:如何设计互相关注业务场景
    数字孪生在工业制造中的应用领域及技术体系构建
    Bert性能提升14.8%,MindSpore算子自动生成技术详解
    Android11编译第五弹:开启VPN权限
    郑慧娟:基于统一大市场的数据资产应用场景与评估方法研究
    this硬绑定
  • 原文地址:https://blog.csdn.net/molihuakai_118/article/details/126207576