ReentrantLock源码阅读(1)(JDK1.8)


前言

最近在使用Java 并发包时遇到一些问题,感觉对于其还是不够了解,故开始着手阅读相关源码。


ReentrantLock(JDK 1.8)

实现了Lock接口

public interface Lock {
  
    void lock();
  
    void lockInterruptibly() throws InterruptedException;
  
    boolean tryLock();

    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    void unlock();

    Condition newCondition();
}

Sync类

其内部抽象类,进一步继承了AbstractQueuedSynchronizer类,用于后续实现公平和非公平锁

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

protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
  	// 如果当前线程没有获得锁则无法调用成功释放,抛出IllegalMonitorStateException
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

NonfairSync类

NonfairSync类,静态final,继承自Sync。

static final class NonfairSync extends Sync {
    final void lock() {
        if (compareAndSetState(0, 1))	// 1
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);	// +1
    }

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

FairSync类

static final class FairSync extends Sync {

    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) {
          	// 如果队列前面没有节点,且当前锁并未被其他线程持有,则成功
            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;
    }
}

重要属性和方法

private final Sync sync;

两个构造函数,默认为非公平锁

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

public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}
public void lock() {
    sync.lock();	// 调用Sync实现
}

public void unlock() {
  	sync.release(1);	// 调用Sync实现
}
public Condition newCondition() {
    return sync.newCondition();	// return new ConditionObject();
}

总结

lock()和unlock()的调用过程如下,本质锁其实就是一个volatile state值,在加上unsafe中的一些操作实现
lock()过程
unlock()过程
ReentrantLock相关继承类图如下图所示。
ReentrantLock相关继承类图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值