JUC - 可重入锁ReentrantLock

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lipinganq/article/details/80550383

一. ReentrantLock初识

上一篇介绍了实现同步锁的基础AQS:JUC - 队列同步器AQS
1. ReentrantLock具有与 synchronized 相同的一些基本行为和内存语义,但是比synchronized更加灵活强大
2. ReentrantLock是基于AQS实现的,上一篇介绍了AQS:JUC - 队列同步器AbstractQueuedSynchronizer
3. ReentrantLock有公平锁和非公平锁,默认是非公平锁

ReentrantLock使用模板:

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
}

二. ReentrantLock可重入

  1. ReentrantLock的实现以状态state=0表示锁没有被任何线程持有
  2. 当线程A第一次获取到锁(lock),状态state变为1
  3. 线程A可以再次直接获取锁,其他线程无法获取,状态state每次增1,这就是线程的可重入
  4. 当线程A每次释放锁(unlock),状态state减1
  5. 当AQS队列状态state减为0,表示线程A释放了锁,锁可以被其他线程获取

三. ReentrantLock的结构

ReentrantLock根据传入构造方法的布尔型参数实例化出Sync的实现类FairSync和NonfairSync,分别表示公平的Sync和非公平的Sync

3.1 ReentrantLock继承结构

这里写图片描述

3.2 ReentrantLock构造函数

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

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

四. 公平锁与非公平锁

Sync是以同步队列的状态state表示线程是否获取到锁

  • 当state=0,表示锁没有被持有过
  • ReentrantLock每次调用lock(),state增加1,这就是锁的可重入,同一个锁最多能重入Integer.MAX_VALUE次,也就是2147483647
  • ReentrantLock每次调用unlock(),state就减1,直到state=0就表示锁完全释放

4.1 锁的基本实现Sync

abstract static class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = -5179523762034025860L;

    abstract void lock();

    /**
     * 非公平锁尝试获取锁
     * 1. 获取当前线程
     * 2. 获取同步队列当前状态state
     * 3. 当state=0,使用CAS设置state=acquires,设置当前线程为独占,返回true,表示获取锁成功
     * 4. 当当前线程已经持有锁,再次尝试获取锁,可重入,更新state值,返回true
     * 5. 否则返回false
     * */
    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. 每次释放,说明线程已持有锁,状态state值减releases
     * 2. 当state减到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;
    }

    protected final boolean isHeldExclusively() {
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

    final ConditionObject newCondition() {
        return new ConditionObject();
    }

    /**
     * 获取当前占有锁的线程
     * */
    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }

    /**
     * lock被调用了几次,ReentrantLock每次调用lock增加1
     * */
    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {
        return getState() != 0;
    }

    private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

4.2 非公平锁NonFairSync

顾名思义,非公平锁就是获取锁的机会是不公平的,它不是按照线程在同步队列的顺序来获取锁,而是每次线程获取锁时,会尝试去获取锁,如果锁没有没持有或刚好锁被其他线程是否,当前线程就有可能获取到锁,这对更早进入队列的线程是不公平的

static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

4.3 公平锁FairSync

公平锁就是多个线程获取锁的机会是公平的,获取锁的机会是按照进入队列的时间的先后顺序决定的,更早进入队列的可以先获取锁
公平锁与非公平锁尝试获取锁tryAcquire方法的区别在于:当锁没有被持有,当前线程尝试获取锁之前,首先查询队列中是否存在等待获取锁的线程 - hasQueuedPredecessors()

  • 如果队列中存在等待获取锁的线程,尝试获取失败,当前线程加入同步队列尾
  • 如果队列中不存在,进行下一步判断
static final class FairSync extends Sync {
    private static final long serialVersionUID = -3000897897090466540L;

    final void lock() {
        acquire(1);
    }

    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;
    }
}

public final boolean hasQueuedPredecessors() {
    Node t = tail; 
    Node h = head;
    Node s;
    return h != t && ((s = h.next) == null || s.thread != Thread.currentThread());
}

五. 获取锁

5.1 获取锁 - lock

  1. 如果该锁没有被另一个线程持有并立即返回(state=0),则锁定获取,将锁定保持计数设置为1
  2. 如果当前线程已经拥有锁定,则保持计数state会加1,并且该方法立即返回
  3. 如果锁由另一个线程保存,则当前线程因为线程调度被禁用,并处于休眠状态,直到获取锁,此时锁定保持计数设置为1
/**
 * 获取锁,非公平锁和公平锁都有自己的实现
 */
public void lock() {
    sync.lock();
}

5.2 未被中断的线程获取锁 - lockInterruptibly

如果当前线程未被中断,则获取锁
如果锁被另一个线程保持,则出于线程调度目的,当前线程会被禁用(休眠),发生下面2种情况之一,会唤醒线程:

  1. 锁由当前线程获得
  2. 其他某个线程中断当前线程

如果当前线程:

  1. 在进入此方法时已经设置了该线程的中断状态;或者
  2. 在等待获取锁的同时被中断

则抛出 InterruptedException,并且清除当前线程的已中断状态。

/**
 * 如果当前线程未被中断,则获取锁
 * 如果当前线程被中断,抛出InterruptedException异常
 */
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}

六. 释放锁

释放锁具体实现详见:释放独占锁

/**
 * 试图释放此锁
 * 如果当前线程是此锁所有者,则将保持计数减 1
 * 如果保持计数现在为 0,则释放该锁
 * 如果当前线程不是此锁的持有者,则抛出 IllegalMonitorStateException
 *
 * @throws IllegalMonitorStateException if the current thread does not hold this lock
 */
public void unlock() {
    sync.release(1);
}

七. 公平锁实例

公平锁是指多个线程同时等待同一个锁时,必须按照申请锁的时间顺序来依次获取锁
事实上,公平锁机制往往没有非公平锁的效率高

package com.example.demo.juc;

import com.example.demo.ReentrantLock;

import java.util.ArrayList;
import java.util.concurrent.Callable;

public class FairLockTest {
    static class Product {
        private int count;
        ReentrantLock fairLock = new ReentrantLock(true);

        public void inc() throws InterruptedException {
            fairLock.lock();
            try{
                System.out.println("执行线程:" + Thread.currentThread().getName());
                count++;
                System.out.println("增加后count = " + count);
            } finally {
                fairLock.unlock();
            }
        }
    }

    static class LockThread extends Thread {
        private int state;
        private Product pro = null;

        public LockThread(int state, Product pro){
           super("Thread - " + state);
           this.state = state;
           this.pro = pro;
        }

        @Override
        public void run() {
            try {
                this.pro.inc();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Product product = new Product();

        for(int i = 0; i < 10; i++){
            new LockThread(i, product).start();
            Thread.sleep(5);// 暂缓线程的创建,便于顺序进入同步队列
        }
    }
}

运行结果:
线程是按数字顺序依次进入同步队列,获取锁的顺序也是根据进入队列的先后顺序
这里写图片描述

八. 非公平锁实例

package com.example.demo.juc;

import com.example.demo.ReentrantLock;

import java.util.ArrayList;
import java.util.concurrent.Callable;

public class NonFairLockTest {
    static class Product {
        private int count;
        ReentrantLock fairLock = new ReentrantLock();

        public void inc() throws InterruptedException {
            fairLock.lock();
            try{
                System.out.println("执行线程:" + Thread.currentThread().getName());
                count++;
                System.out.println("增加后count = " + count);
            } finally {
                fairLock.unlock();
            }
        }
    }

    static class LockThread extends Thread {
        private int state;
        private Product pro = null;

        public LockThread(int state, Product pro){
            super("Thread - " + state);
            this.state = state;
            this.pro = pro;
        }

        @Override
        public void run() {
            try {
                this.pro.inc();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Product product = new Product();

        for(int i = 0; i < 10; i++){
            new LockThread(i, product).start();
//            Thread.sleep(5);// 暂缓线程的创建,便于顺序进入同步队列
        }
    }
}

运行结果:
取消线程的暂缓创建,则多个线程会竞争获取锁,任一等待锁的线程输出结果就不会按照数字顺序
这里写图片描述

九. 条件队列Condition的实例

任意一个Java对象,都拥有一组监视器方法(定义在java.lang.Object上),主要包括wait()、
wait(long timeout)、notify()以及notifyAll()方法,这些方法与synchronized同步关键字配合,可以实现等待/通知模式。Condition接口也提供了类似Object的监视器方法,与Lock配合可以实现等待/通知模式,但是这两者在使用方式以及功能特性上还是有差别的
ConditionObject是同步器AbstractQueuedSynchronizer的内部类,因为Condition的操作需要获取相关联的锁,所以作为同步器的内部类也较为合理。每个Condition对象都包含着一个队列(以下称为等待队列),该队列是Condition对象实现等待/通知功能的关键

  • 等待队列是一个FIFO的队列,在队列中的每个节点都包含了一个线程引用,该线程就是
    在Condition对象上等待的线程
  • 获取一个Condition必须通过Lock的newCondition()方法,所以Condition是依赖Lock对象的
  • Condition的使用方式比较简单,需要注意在调用方法前获取锁
  • 如果一个线程调用了Condition.await()方法,那么该线程将会释放锁、构造成节点加入等待队列并进入等待状态
  • 调用Condition的signal()方法,将会唤醒在等待队列中等待时间最长的节点(首节点),在
    唤醒节点之前,会将节点移到同步队列中
  • Condition的signalAll()方法,相当于对等待队列中的每个节点均执行一次signal()方法,效
    果就是将等待队列中所有节点全部移动到同步队列中,并唤醒每个节点的线程

十. 源码

基于AQS的实现,AQS参考:JUC - 队列同步器AQS

package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;
import java.util.Collection;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    private final Sync sync;

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

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

    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        abstract void lock();

        /**
         * 非公平锁尝试获取锁
         * 1. 获取当前线程
         * 2. 获取同步队列当前状态state
         * 3. 当state=0,使用CAS设置state=acquires,设置当前线程为独占,返回true,表示获取锁成功
         * 4. 当当前线程已经持有锁,再次尝试获取锁,可重入,更新state值,返回true
         * 5. 否则返回false
         * */
        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. 每次释放,说明线程已持有锁,状态state值减releases
         * 2. 当state减到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;
        }

        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        /**
         * 获取当前占有锁的线程,如果锁不被任何线程持有,返回null
         * */
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        /**
         * lock被调用了几次,ReentrantLock每次调用lock增加1
         * */
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    /**
     * 非公平锁实现
     * */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    /**
     * 公平锁实现
     * 如果当前队列存在等待获取锁的线程,添加到节点尾
     * */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                // hasQueuedPredecessors判断队列是否存在等待获取锁的线程
                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;
        }
    }

    /**
     * 获取锁,非公平锁和公平锁都有自己的实现
     */
    public void lock() {
        sync.lock();
    }

    /**
     * 如果当前线程未被中断,则获取锁
     * 如果当前线程被中断,抛出InterruptedException异常
     */
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    /**
     * 尝试获取锁
     * */
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    /**
     * 如果锁在给定等待时间内没有被另一个线程获取,且当前线程未被中断,则获取该锁
     * 如果超出了指定的等待时间,则返回值为 false。如果该时间小于等于 0,则此方法根本不会等待
     *
     * @throws InterruptedException if the current thread is interrupted
     * @throws NullPointerException if the time unit is null
     */
    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    /**
     * 试图释放此锁
     * 如果当前线程是此锁所有者,则将保持计数减 1
     * 如果保持计数现在为 0,则释放该锁
     * 如果当前线程不是此锁的持有者,则抛出 IllegalMonitorStateException
     *
     * @throws IllegalMonitorStateException if the current thread does not hold this lock
     */
    public void unlock() {
        sync.release(1);
    }

    /**
     * 查询当前线程保持此锁的次数
     */
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    /**
     * 查询当前线程是否保持此锁
     */
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /**
     * 查询此锁是否由任意线程持有
     * 此方法用于监视系统状态,不用于同步控制
     */
    public boolean isLocked() {
        return sync.isLocked();
    }

    /**
     * 是否为公平锁
     */
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    /**
     * 返回目前拥有此锁的线程,如果此锁不被任何线程拥有,则返回 null
     */
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /**
     * 查询队列中是否有些线程正在等待获取此锁
     *
     * 注意,因为随时可能发生取消,所以返回 true并不保证有其他线程将获取此锁。此方法主要用于监视系统状态
     */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * 查询给定线程是否正在等待获取此锁
     *
     * 注意,因为随时可能发生取消,所以返回 true 并不保证此线程将获取此锁。此方法主要用于监视系统状态
     */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /**
     * 返回队列中正等待获取此锁的线程估计数。该值仅是估计的数字
     * 因为在此方法遍历内部数据结构的同时,线程的数目可能动态地变化。此方法用于监视系统状态,不用于同步控制
     */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /**
     * 返回一个 collection,它包含队列中可能正等待获取此锁的线程
     * 因为在构造此结果的同时实际的线程 set可能动态地变化,所以返回的 collection 仅是尽力的估计值。
     * 所返回 collection 中的元素没有特定的顺序。此方法用于加快子类的构造速度,以提供更多的监视设施
     */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    public Condition newCondition() {
        return sync.newCondition();
    }

    /**
     * 查询是否有些线程正在等待与此锁有关的给定条件
     *
     * 注意,因为随时可能发生超时和中断,所以返回 true 并不保证将来某个 signal 将唤醒线程。此方法主要用于监视系统状态
     */
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * 返回等待与此锁相关的给定条件的线程估计数
     *
     * 注意,因为随时可能发生超时和中断,所以只能将估计值作为实际等待线程数的上边界。此方法用于监视系统状态,不用于同步控制
     */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * 返回一个 collection,它包含可能正在等待与此锁相关给定条件的那些线程
     *
     * 因为在构造此结果的同时实际的线程 set 可能动态地变化,所以返回 collection 的元素只是尽力的估计值
     * 所返回 collection 中的元素没有特定的顺序。此方法用于加快子类的构造速度,提供更多的条件监视设施
     */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]");
    }
}

猜你喜欢

转载自blog.csdn.net/lipinganq/article/details/80550383