java ReentrantLock NonfairSync和FairSync源码实现

3 篇文章 0 订阅
2 篇文章 0 订阅

继续学习java 锁 接上篇文章ReentrantLock

1.ReentrantLock 构造

ReentrantLock默认构造是非公平锁NonfairSync,传入true时是公平锁 FairSync,ReentrantLock构造如下

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

2.非公平锁 NonfairSync

源代码如下,后面继续学习Sync

	static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;
        final void lock() {
            if (compareAndSetState(0, 1))//继承的 AbstractQueuedSynchronizer
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);//继承的AbstractQueuedSynchronizer
        }
        protected final boolean tryAcquire(int acquires) {
        	//继承的Sync的方法 nonfairTryAcquire
            return nonfairTryAcquire(acquires);
        }
    }

NonfairSync 有两个方法 lock 和 tryAcquire,lock用于 执行锁定

3.公平锁 FairSync

公平锁和非公平锁的去标在于tryAcquire方法的实现

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

不做过多介绍,在后面AbstractQueuedSynchronizer中学习

4.Sync

ReentrantLock 内部类非公平锁 NonfairSync 和 公平锁都继承了 Sync

private final Sync sync;

继承AbstractQueuedSynchronizer

abstract static class Sync extends AbstractQueuedSynchronizer 

抽象方法lock,用于锁定

abstract void lock();

nonfairTryAcquire

执行非公平tryLock。tryAcquire在子类中实现,但两者都需要trylock方法的非致命尝试。

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

ReentrantLock中的使用

	public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

非公平锁 NonfairSync 的使用

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

tryRelease

		// 尝试释放锁
		protected final boolean tryRelease(int releases) {
            // c:释放锁后的新state
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            // free:当前锁是否已经空闲,如果是则说明当前锁的所有重入都已解锁
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            // 因为锁为独占式获取,所以设置state值不需要同步措施
            setState(c);
            return free;
        }

ReentrantLock中的使用

	public void unlock() {
        sync.release(1);
    }
	public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

isHeldExclusively

	//虽然我们通常必须在所有者之前读取状态,
	//我们不需要这样做来检查当前线程是否为所有者
	protected final boolean isHeldExclusively() {
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

newCondition

ReentrantLock 使用newCondition 调用的sync.newCondition()

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

Condition条件实现原理

  1. lock.newCondition(),new一个ConditionObject对象,ConditionObject有一个单向等待队列
  2. condition等待队列:线程已经拿到锁,但是因为不满足某个条件,被放入等待队列并释放锁,不能获取锁,AQS同步队列:线程抢锁失败,被放入AQS阻塞队列,等前面线程释放锁之后自己再获取锁
  3. await():当前线程T加入条件等待队列 释放锁 park()当前线程,signal():当前线程T节点出条件等待队列 T节点加入AQS同步队列 unpark()T线程

readObject

从流中重新构造实例(即反序列化它)

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

其它方法

      // 从外部类中继的方法
        //获取拿到锁的线程 没有则返回null
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }
        //查询当前线程对该锁的持有次数,也就是调用 lock() 方法的次数
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }
        //是否被锁
        final boolean isLocked() {
            return getState() != 0;
        }

5.AbstractQueuedSynchronizer

ReentrantLock 的内部类 Sync 继承了 AbstractQueuedSynchronizer

AbstractOwnableSynchronizer

AbstractQueuedSynchronizer 继承了AbstractOwnableSynchronizer

	protected AbstractOwnableSynchronizer() { }
    private transient Thread exclusiveOwnerThread;
    protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }
    protected final Thread getExclusiveOwnerThread() {
        return exclusiveOwnerThread;
    }

AbstractQueuedSynchronizer

serialVersionUID
AbstractQueuedSynchronizer()
Node
head
tail
state
getState()
setState(int)
compareAndSetState(int, int)
spinForTimeoutThreshold
enq(Node)
addWaiter(Node)
setHead(Node)
unparkSuccessor(Node)
doReleaseShared()
setHeadAndPropagate(Node, int)
cancelAcquire(Node)
shouldParkAfterFailedAcquire(Node, Node)
selfInterrupt()
parkAndCheckInterrupt()
acquireQueued(Node, int)
doAcquireInterruptibly(int)
doAcquireNanos(int, long)
doAcquireShared(int)
doAcquireSharedInterruptibly(int)
doAcquireSharedNanos(int, long)
tryAcquire(int)
tryRelease(int)
tryAcquireShared(int)
tryReleaseShared(int)
isHeldExclusively()
acquire(int)
acquireInterruptibly(int)
tryAcquireNanos(int, long)
release(int)
acquireShared(int)
acquireSharedInterruptibly(int)
tryAcquireSharedNanos(int, long)
releaseShared(int)
hasQueuedThreads()
hasContended()
getFirstQueuedThread()
fullGetFirstQueuedThread()
isQueued(Thread)
apparentlyFirstQueuedIsExclusive()
hasQueuedPredecessors()
getQueueLength()
getQueuedThreads()
getExclusiveQueuedThreads()
getSharedQueuedThreads()
toString()
isOnSyncQueue(Node)
findNodeFromTail(Node)
transferForSignal(Node)
transferAfterCancelledWait(Node)
fullyRelease(Node)
owns(ConditionObject)
hasWaiters(ConditionObject)
getWaitQueueLength(ConditionObject)
getWaitingThreads(ConditionObject)
ConditionObject
unsafe
stateOffset
headOffset
tailOffset
waitStatusOffset
nextOffset
compareAndSetHead(Node)
compareAndSetTail(Node, Node)
compareAndSetWaitStatus(Node, int, int)
compareAndSetNext(Node, Node, Node)

AbstractQueuedSynchronizer的具体实现后面在学习

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值