Java之JUC locks包锁实现
ReentrantLock 可重入锁 基于线程队列来实现
- 首先看锁持有者线程 AbstractOwnableSynchronizer,其内部仅仅包含一个执行线程
public abstract class AbstractOwnableSynchronizer
implements java.io.Serializable {
protected AbstractOwnableSynchronizer() { }
// 执行线程
private transient Thread exclusiveOwnerThread;
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
protected final Thread getExclusiveOwnerThread() {
return exclusiveOwnerThread;
}
}
- 其子类AbstractQueuedSynchronizer, public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer,其是一个链表结构,存储了,需要加锁的全部线程;
/**
* <pre>
* +------+ prev +-----+ +-----+
* head | | <---- | | <---- | | tail
* +------+ +-----+ +-----+
* </pre>
* /
其中每一个节点源码如下,包含了上一个节点引用,下一个节点引用,是否是共享模式或独占模式,还有节点状态
static final class Node {
/** Marker to indicate a node is waiting in shared mode 标记共享模型*/
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode 标记独占模型*/
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled 标记线程已取消获取锁 */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking 标记线程需要获取锁,等待获得*/
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition 标记线程正在等待获取锁 */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate 标记是共享锁需要无条件传播
*/
static final int PROPAGATE = -3;
// 等待状态,上面的值
volatile int waitStatus;
// 链表结构,上一个节点
volatile Node prev;
// 链表结构,下一个节点
volatile Node next;
// 本节点线程
volatile Thread thread;
// 下一个等待者,标记是独占锁,还是共享锁
Node nextWaiter;
// 返回是共享模式
final boolean isShared() {
return nextWaiter == SHARED;
}
// 上一个node, 检查是否空
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() { // Used to establish initial head or SHARED marker
}
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
AbstractQueuedSynchronizer 是链表结构,内部包含头部,尾部,状态
//链表头
private transient volatile Node head;
// 链表尾部
private transient volatile Node tail;
// 状态
private volatile int state;
其为了保证原子性,使用了Unsafe 类
用来设置链表的头,尾部和Node节点状态
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long stateOffset;// 状态对于对象头的内存地址偏移量
private static final long headOffset;// 链表头节点对于对象头的内存地址偏移量
private static final long tailOffset;// 链表尾部节点对于对象头的内存地址偏移量
private static final long waitStatusOffset;// Node节点状态对于对象头的内存地址偏移量
private static final long nextOffset;// Node节点的下一个节点对于对象头的内存地址偏移量
static {
try {
stateOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
headOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("head"));
tailOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
waitStatusOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("waitStatus"));
nextOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("next"));
} catch (Exception ex) { throw new Error(ex); }
}
其增加node节点,原子性的,
/**
* Creates and enqueues node for current thread and given mode.
* 增加线程Node,
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
*/
private Node addWaiter(Node mode) {
// 新建node,是否是共享性的
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) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
// 未设置成功,循环设置
enq(node);
return node;
}
/**
* 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) {
for (;;) {
// 如果尾部是空,直接设置一个头和尾部,然后增加到尾部
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
获得锁
// 获得锁,如果没有获得锁则一直到获得锁
public final void acquire(int arg) {// 参数为重入次数
if (!tryAcquire(arg) && // 先有子类判断是否获得, 如果没有获得,则加入队列,如果加入队列成功则中断本线程
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
// 获得锁,如果没有获得锁则中断
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))// 如果没有获得锁则中断
// 加入队列,并再次判断
doAcquireInterruptibly(arg);
}
- ReentrantLock 的静态内部类 Sync extends AbstractQueuedSynchronizer, 其继承了虚拟的队列锁
// 由子类实现
abstract void lock();
// 非公平锁加锁
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;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
// Methods relayed from outer class
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {
return getState() != 0;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}