6、ReentrantLock源码

一、ReentrantLock简介

 ReentrantLock是与关键字synchronized对标的一类锁,  ReentrantLock除掉实现公平锁、可中断锁外不建议其他场景使用ReentrantLock。 原因1:synchronized经过(无锁->偏向锁->轻量级锁->自旋锁->重量及锁优化性能不比ReentrantLock差,其实ReentrantLock就是一个自旋锁),原因2:ReentrantLock需要自己释放锁使用麻烦。

二、ReentrantLock实现锁类型

功能可重入锁不可重入公平锁非公平锁独占锁可中断锁
Synchronized支持不支持 不支持支持支持不支持
ReentrantLock支持不支持支持支持支持支持

三、各类型锁特点

公平锁:多线程按照申请锁的顺序获取锁,性能差保证顺序。
非公平锁:获取锁顺序和申请锁的顺序无关,大部分的锁都支持非公平锁,性能好。
可重入锁:当一个线程获取资源(锁),别的线程再次获取,不会出现异常(线程等待)。
不可重入锁:当一个线程获取锁后,别的线程无法再次获取锁。(实现需要自定义)
独占锁:一个线程获取资源(锁),其他线程不能获取该资源。(syn,rl都是队列独占锁)
可中断锁:一个线程等待另外一个线程释放资源,超时后不在等待。

四、ReentrantLock源码解读

NonfairSync:非公平锁

FairSync:公平锁

 public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    /** 同步器定义 */
    private final Sync sync;

    /**
     * 继承AQS信号状态控制实现锁同步。
     * NonfairSync继承Sync实现非公平锁
     * FairSync继承Sync实现公平锁
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * 定义lock接口提供给NonfairSync、airSync实现         
         */
        abstract void lock();

        /**
         * 尝试非公平方式获取锁
         * 成功返回true失败返回false
         */
        final boolean nonfairTryAcquire(int acquires) {
            //获取当前线程
            final Thread current = Thread.currentThread();
            //获取state值,0表示无锁,1表示已经获取锁
            int c = getState();
            if (c == 0) {
                //如果state=0修改为acquires
                if (compareAndSetState(0, acquires)) {
                    //设置当前拥有独占访问的线程
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            //当前线程等于持有锁线程
            else if (current == getExclusiveOwnerThread()) {
                //TODO 理解这块需要理解释放流程
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
        
        //尝试释放锁
        protected final boolean tryRelease(int releases) {
            //释放锁,修改state=0
            int c = getState() - releases;
            //如果当前线程不等于已持有线程抛出异常
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            //如果state被修改为0说明成功释放锁
            if (c == 0) {
                free = true;
                //持有线程重置为null
                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();
        }
        
        //当前线程占有锁的数量,不持有锁为0,否则1
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        //判断当前线程是否持有锁,持有true,不持有false
        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * TODO 干什么用?
         */
        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() {
            //修改state状态值为1,体现非公平方式获取锁
            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);
        }

        /**
         * 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();
            int c = getState();
            if (c == 0) {
                //AQS方法 TODO
                if (!hasQueuedPredecessors() &&
                    //修改state=0为acquires
                    compareAndSetState(0, acquires)) {
                    //设置当前线程为持有线程    
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            //TODO 待理解
            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 ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * 实例化锁类型
     * true:公平锁
     * false:非公平锁
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

    //获取lock
    public void lock() {
        sync.lock();
    }
   
   /**
    * 获取锁
    * 如果该锁没有被另一个线程保持,则获取该锁并立即返回,将锁的保持计数设置为 1
    * 如果当前线程已经保持该锁,则将保持计数加 1,并且该方法立即返回
    * 如果该锁被另一个线程保持,则出于线程调度的目的,禁用当前线程,并且在获得锁之前,该线程将一 
    * 直处于休眠状态,此时锁保持计数被设置为 1
    * 备注:锁计数由tryAcquire实现
    */
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }
   
   /**
    *尝试获取锁成功返回true失败返回false
    */
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
    
    /**
    * 超时等待的方式获取锁,如果超时未获取返回false
    * 源码解读:AQS源码分析
    */
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }
   
   /**
    * 锁释放
    * 源码解读:AQS源码分析
    */
    public void unlock() {
        sync.release(1);
    }

    //初始化队列
    public Condition newCondition() {
        return sync.newCondition();
    }

    //当前线程占有锁的数量,不持有锁为0,否则1
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    //判断持有线程是否等于当前线程(判断线程拥有情况)
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    //判断当前线程是否持有锁,持有true,不持有false
    public boolean isLocked() {
        return sync.isLocked();
    }
    
    //判断当前锁是公平锁,是返回true
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    //返回拥有锁的线程
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /**
     *是否有线程等待排队获取锁,是返回true
     *源码解读:AQS源码分析 TODO
     */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
    * 查询指定线程是否在等待获取锁
    * 源码解读:AQS源码分析 TODO
    */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

   /**
    * 查询等待获取锁的线程数
    * 源码解读:AQS源码分析 TODO
    */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

   /**
    * 返回等待获取锁的线程集合
    * 源码解读:AQS源码分析 TODO
    */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }
    
    /**
    * 判断是否有线程在condition队列等待
    * 源码解读:AQS源码分析 TODO
    */
    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);
    }
   
   /**
    * 判断在condition队列等待的线程数量
    * 源码解读:AQS源码分析 TODO
    */
    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);
    }
   
   /**
    * 返回在condition队列等待的线程集合
    * 源码解读:AQS源码分析 TODO
    */
    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() + "]");
    }
}


参考文档:

  1.  ReentrantLock(重入锁)功能详解和应用演示
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值