ReentrantLock的原理

23 篇文章 0 订阅

ReentrantLock的底层

ReentrantLock的源码:

(1)ReentrantLock是Lock的子类,支持序列化

(2)ReentrantLock里面有一抽象的静态内部类Sync(继承了AQS),并且有一类型为该类Sync的成员变量

​ 有两个Sync的子类,表示公平锁和非公平锁

(3)ReentrantLock里面的方法都是通过sync调用其里面的方法进行实现的

(4)ReentrantLock里面是默认使用非公平锁的,如果要使用公平锁,则在lock定义的时候需要传入参数true

state初始化为0,表示未锁定状态。A线程lock时,会调用tryAcquire独占该锁并将state+acquires(一般acquires就是1)

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

    private final Sync sync;

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

		/**
		* 加锁
		*/
        abstract void lock();

		/**
		* 非公平锁尝试获取锁
		*/
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 0 表示未锁定状态
            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;
        }
		/**
		* 尝试释放资源,成功则返回true,失败则返回false。
		*/
        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;
        }
		/**
		* 该线程是否正在独占资源。只有用到condition才需要去实现它
		*/
        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

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

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

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

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

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

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

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
  
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    public void unlock() {
        sync.release(1);
    }

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


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

   
    protected Thread getOwner() {
        return sync.getOwner();
    }

   
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }


    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }


    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

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

   
    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() + "]");
    }
}

重入锁与非重入锁实现

ReentrantLock是一个可重入锁,尝试获取锁tryAcquire方法是不会引起阻塞的,lock方法是会引起阻塞的

先列举出其源码:

重入锁尝试获取锁的源码如下:

/**
    * 尝试获取资源,成功则返回true,失败则返回false。
     */
    protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        //首先判断当前是否已经有线程获取到锁 , 0表示没有获取到锁
        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;
    }
  • 可重入锁尝试获取资源的方法逻辑是,首先判断当前是否已经有线程获取到锁
  • 若当前锁没有被占用,则当前线程可以进行占用到这个锁,变为独占锁
  • 若当前锁被占用了,这个时候要比较这个占用的锁的线程是不是当前线程,如果是,也相当于获取到锁的。着也是与非重入锁差别的一点

若改为非重入锁,尝试获取锁的源码如下:

/**
    * 尝试获取资源,成功则返回true,失败则返回false。
     */
    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;
            }
        }
        return false;
    }
  • 不可重入锁尝试获取资源的方法逻辑是,首先判断当前是否已经有线程获取到锁
  • 若当前锁没有被占用,则当前线程可以进行占用到这个锁,变为独占锁
  • 若当前锁被占用了,这个时候就直接返回获取锁失败false(它不会去判断占用这个锁的线程是不是就是当前线程)

公平锁与非公平锁实现

ReentrantLock里面是默认使用非公平锁的,如果要使用公平锁,则在lock定义的时候需要传入参数true

state初始化为0,表示未锁定状态。A线程lock时,会调用tryAcquire独占该锁并将state+acquires

(1)公平锁与非公平锁的区别:

体现在获取锁(调用lock方法)的时候,非公平锁是先进行CAS操作,进行判断是否可以直接获取到锁,则公平锁就直接进行获取锁的操作

// 非公平锁
static final class NonfairSync extends Sync {
	private static final long serialVersionUID = 7316153563782823691L;
     /**
     * 先进行CAS判断,是否可以获取到锁,如果可以获取到锁,就将当前独占的锁设置为当前进程
     */
    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }
	// nonfairTryAcquire查看上面Sync中的
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

// 公平锁
static final class FairSync extends Sync {
    private static final long serialVersionUID = -3000897897090466540L;
	/**
	* state 为 0 表示未锁定状态,加锁,就给state加1
	*/
    final void lock() {
        acquire(1);
    }

    /**
    * 尝试获取资源,成功则返回true,失败则返回false。
     */
    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 void acquire(int arg) {
        if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
}

AQS中的CAS操作,通过预期值与内存的值进行比较,若相同,则进行更新

protected final boolean compareAndSetState(int expect, int update) {
    // unsafe一般用于原子Atmoic类中,底层相关的东西
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值