前言
最近在使用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中的一些操作实现
ReentrantLock相关继承类图如下图所示。