abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
abstract void lock();//主要为了子类可以尝试快速非公平的获取锁
final boolean nonfairTryAcquire(int acquires) {//非公平尝试获取锁,公平与非公平实现的trylock方法都会调用这个来尝试非公平的获取一次
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {//当前状态为0代表锁没有被获取,CAS设置状态,成功后setExclusiveOwnerThread设置持有锁的线程
if (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;
}
protected final boolean tryRelease(int releases) {//释放锁
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())//释放锁的当前线程必须是持有锁的线程,否则无法释放
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {//因为可重入,所以状态为0时才需要setExclusiveOwnerThread(null)清空持有锁的线程,并且返回true,返回true会在release方法触发唤醒等待锁的线程。只有当前线程完全释放锁,其他线程才可以去得到锁
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {//判断当前线程是否是持有锁的线程
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {//Condition是AQS的等待队列,类似Object的wait和notify,在下一节分析
return new ConditionObject();
}
final Thread getOwner() {//获取当前持有锁的线程
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {//获取重入持有锁的次数
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {//获取当前是否被锁
return getState() != 0;
}
/**
* Reconstitutes this lock instance from a stream.
* @param s the stream
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {//反序列化需要重置锁状态为0
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}