ReentrantLock lock = new ReentrantLock();
try{
//加锁
lock.lock();
//执行业务相关代码
}catch(Excetion e){
}finally{
//释放锁
lock.unlock();
}
ReentrantLock 内置了一个抽象类AbstractQueuedSynchronizer,公平锁类FairSync,非公平锁类NonfairSync
用来执行操作,
构造方法
/**
* Creates an instance of {@code ReentrantLock}.
* 创建一个非公平锁的ReentrantLock实例
* This is equivalent to using {@code ReentrantLock(false)}.
* 等同于用有参构造ReentrantLock(false)
*/
public ReentrantLock() {
sync = new NonfairSync();
}
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
* 根据传入参数创建公平或非公平锁的ReentrantLock实例
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
lock.lock();
/**
* Acquires the lock.
*
* <p>Acquires the lock if it is not held by another thread and returns
* immediately, setting the lock hold count to one.
*
* <p>If the current thread already holds the lock then the hold
* count is incremented by one and the method returns immediately.
*
* <p>If the lock is held by another thread then the
* current thread becomes disabled for thread scheduling
* purposes and lies dormant until the lock has been acquired,
* at which time the lock hold count is set to one.
*/
public void lock() {
//调用内部类sync的lock方法
sync.lock();
}
内部抽象类Sync的lock方法是一个抽象方法,由非公平锁类NonfairSync和公平锁类FairSync来实现
NonfairSync类lock方法实现
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
* 忽略等待队列是否有线程在等待,先尝试修改stata字段状态.
*/
final void lock() {
if (compareAndSetState(0, 1))
//获取锁成功,设置当前占有锁的线程是当前线程,这里是为锁重入 做准备
setExclusiveOwnerThread(Thread.currentThread());
else
//调用父类AbstractQueuedSynchronizer的acquire方法;
acquire(1);
}
AbstractQueuedSynchronizer.acquire方法
public final void acquire(int arg) {
//调用子类实现的tryAcquire方法尝试获取锁,由NonfairSync和FairSync实现
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
NonfairSync.tryAcquire
protected final boolean tryAcquire(int acquires) {
//调用父类Sync的nonfairTryAcquire方法
return nonfairTryAcquire(acquires);
}
Sync的nonfairTryAcquire方法
//final方法,不允许重写
final boolean nonfairTryAcquire(int acquires) {
//获取当前线程
final Thread current = Thread.currentThread();
//获取stata的值
int c = getState();
//为0说明当前没有线程获取锁,用CAS修改stata的值为传入的值,获取锁
if (c == 0) {
if (compareAndSetState(0, acquires)) {
//获取成功,设置占用锁的线程为当前线程
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
//stata不为0,判断占用锁的线程是当前线程.计算stata加上acquires
int nextc = c + acquires;
//nextc 不应该小于0的
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
//设置stata
setState(nextc);
return true;
}
return false;
}
FairSync.tryAcquire方法
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//hasQueuedPredecessors判断是否有等待线程,有就返回true,
//compareAndSetState(0, acquires)用CAS操作修改stata值
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
//当前没有线程等待,尝试获取锁成功,设置占用锁线程
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
//占用锁的线程为当前线程,用stata值加上acquires赋值给stata
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
hasQueuedPredecessors方法在AbstractQueuedSynchronizer抽象类中
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
//存放等待执行的队列为双向链表.当链表中没有等待线程时tail和head是一个Node对象,且该对象的next属性为null.
//h != t 等待队列初始化时head和tail是同一个对象.
//s = h.next) == null || s.thread != Thread.currentThread()说明有线程正在初始化等待队列.
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
接下来是上锁失败的动作.
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
addWaiter方法
/**
* Creates and enqueues node for current thread and given mode.
*
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
*/
private Node addWaiter(Node mode) {
//传入的node是Node.EXCLUSIVE,
/** Marker to indicate a node is waiting in exclusive mode */
//static final Node EXCLUSIVE = null;
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
//如果pred即队列尾部不为空,说明已经有等待的线程了,把当前线程加入到队列尾部
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
//enq方法
/**
* Inserts node into queue, initializing if necessary. See picture above.
* @param node the node to insert
* @return node's predecessor
*/
private Node enq(final Node node) {
//第一次进入循环结束后队列中的head和tail是同一个.该Node对象的线程属性,前一个元素,后一个元素都为空
for (;;) {
Node t = tail;
if (t == null) { // Must initialize(必须初始化)
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;//将待添加的Node元素前一个元素设置为t即tail
if (compareAndSetTail(t, node)) {//将待添加的Node元素设置到队列尾部
t.next = node;
return t;
}
}
}
}
acquireQueued方法
/**
* Acquires in exclusive uninterruptible mode for thread already in
* queue. Used by condition wait methods as well as acquire.
*
* @param node the node
* @param arg the acquire argument
* @return {@code true} if interrupted while waiting
*/
final boolean acquireQueued(final Node node, int arg) {
//此时的node已添加到等待队列,前一个元素是head或者其他等待Node对象
boolean failed = true;//是否失败标志
try {
boolean interrupted = false;//是否中断标志
for (;;) {
final Node p = node.predecessor();//获取node的前一个元素
if (p == head && tryAcquire(arg)) {//node的前一个元素为head且获取到锁了
setHead(node);//将node设置为head
p.next = null; // help GC将p即原head对象交由GC来回收
failed = false;//失败标志为否
return interrupted;//acquireQueued返回false就不会执行中断操作selfInterrupt();
}
//前一个元素不是头部,自旋直到前一个元素为head
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
//如果自旋结束仍没有获取到执行权,取消加锁
if (failed)
cancelAcquire(node);
}
}
//shouldParkAfterFailedAcquire方法
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)//如果pred元素是正常等待状态,该线程调用park.
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {//等待状态大于0,说明pred等待线程取消或者调用了condition.wait方法,略过pred.
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
//将前一个元素的前一个元素设置到node.pred,node就是当前加锁线程.
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
//Node对象的waitStatus属性是int,默认为0.需要初始化为Node.SIGNAL(-1)
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//parkAndCheckInterrupt方法
/**
* Convenience method to park and then check if interrupted
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//执行park方法,具体实现可以搜索park方法
return Thread.interrupted();//获取当前线程中断状态并清除中断
}
至此lock方法结束.总体流程就是通过CAS来设置锁类中的stata字段来实现是否获取锁,获取不到就添加到等待双向链表队列中并自旋,直到超时或取消.
释放锁
lock.unlock();这里同样是调用的内部属性sync的release方法.
/**
* Attempts to release this lock.
*
* <p>If the current thread is the holder of this lock then the hold
* count is decremented. If the hold count is now zero then the lock
* is released. If the current thread is not the holder of this
* lock then {@link IllegalMonitorStateException} is thrown.
*
* @throws IllegalMonitorStateException if the current thread does not
* hold this lock
*/
public void unlock() {
sync.release(1);
}
/**
* Releases in exclusive mode. Implemented by unblocking one or
* more threads if {@link #tryRelease} returns true.
* This method can be used to implement method {@link Lock#unlock}.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryRelease} but is otherwise uninterpreted and
* can represent anything you like.
* @return the value returned from {@link #tryRelease}
*/
public final boolean release(int arg) {
if (tryRelease(arg)) { //尝试释放锁成功
Node h = head;
if (h != null && h.waitStatus != 0) //head不为空且waitStatus不等于0(不是刚创建状态)
unparkSuccessor(h);
return true;
}
return false;
}
unparkSuccessor唤醒方法
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
//从向等待队列中添加Node对象时每个Node对象都是-1的等待状态
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);//将WaitStatus设置为0
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {//如果下一个待执行Node对象waitStatus大于0则该线程
//已取消获取锁,从队列尾部开始向前查找直到tail等于空或者等于node(head)为止,
//找到距离head最近的一个待获取锁线程对象.并唤醒该node对象的thread线程
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}
ReentrantLock还可以获取condition,由此控制线程等待,这时会将等待队列的node对象waitStatus属性改为CONDITION,这时该线程就会从队列中移除,并保存在ConditionObject的双向队列中,执行signal方法时会从ConditionObject的队列中拿出,重新放入AQS的双向等待队列.
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;