ReentrantLock
リエントラントが同じスレッドが同じロックを複数回取得することができ、対応する内部フィールドがあるだろうと言うことです、リエントラントロックで再入国の回数を記録し、それはそれだけで一つのスレッドを意味し、また、ミューテックスですリエントラントロックを取得することができます。
1.コンストラクタ
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
ReentrantLock
2つのコンストラクタを提供し、コンストラクタは、単に初期化するために使用されるsync
フィールドを、あなたは、デフォルトでは、見ることができるReentrantLock
株式のロックを選択するために、コンストラクタでブールパラメータを使用することも、当然のことながら、ロックの不公正な使用可能。ロックロック公正かつ不当な実装では、2つの内部クラスに依存しますFairSync
とNonfairSync
、その後、どのようなこれらの2つのクラスを学びます:
//非公平锁
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
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;
}
}
内側の2つのクラスコードが非常に短く、別の内部クラスを継承しますSync
。ここで紹介する急いでSync
クラス自体は複雑ではありませんので、このクラスの継承が知っている本のみ必要に使用され、後続の方法の必要性を説明するために、偶然に、クラスをAbstractQueuedSynchronizer(AQS)
することができます。
2.一般的な方法
lock()
public void lock() {
sync.lock();
}
lock
この方法は、ロック機能を提供し、公正かつ不公平ロックロックロック操作は同じではありませんが、不公平なロックの詳細を見てみましょう、公正なロックを説明し、その後。
- 不当なロックロック・ロジック
final void lock() {
//使用CAS操作,尝试将state字段从0修改为1,如果成功修改该字段,则表示获取了互斥锁
//如果获取互斥锁失败,转入acquier()方法逻辑
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
//设置获得了互斥锁的线程
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
非ロックフェアの用語については、使用してlock()
成功のためにmutexを獲得しようとする試みに方法1アップするだろうexclusiveOwnerThread
それ以外の場合は、実行、手段はそれ自身のロックを保持することを、自分自身を指すacquire()
ロジック方法を、次のacquire()
論理的な方法は、1つずつ分析しました。
最初にtryAcquire()
、不公平ロックオーバーライドは、このメソッドは、内部と呼ばれているメソッドSync
クラスnonfairTryAcquire()
。
//从上面的逻辑来看,这里的acquires=1
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//c==0,说明当前处于未加锁状态,锁没有被其他线程获取
if (c == 0) {
//在锁没有被其他线程占有的情况下,非公平锁再次尝试获取锁,获取成功则将exclusiveOwnerThread指向自己
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//执行到这里说明锁已经被占有,如果是被自己占有,将state字段加1,记录重入次数
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
//当nextc达到int类型最大值时会溢出,因此可重入次数的最大值就是int类型的最大值
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
//执行到这里说明:1)锁未被占有的情况下,抢锁失败,说明当前有其他线程抢到了锁;2)锁已经被其他线程占有
//即只要当前线程没有获取到锁,就返回false
return false;
}
//获取state字段,该字段定义在AQS中
protected final int getState() {
return state;
}
//设置state字段
protected final void setState(int newState) {
state = newState;
}
ない現在のスレッドtryAcquire()
のロック取得方法は、最初の実行するaddWaiter(Node.EXCLUSIVE)
パラメータは、前記方法がNode.EXCLUSIVE
定義されている定数でありstatic final Node EXCLUSIVE = null
、それは相互排他ロックされているタグの属性です。addWaiter()
現在のメソッドの役割はにパッケージ化スレッドにあるNode
キューの末尾に、ノード、導入方法CountDownLatch
について詳しくは、クラスの前に説明し、参照することができます興味を持っている友人のソース(JDK 1.8)を探るConcurrentHashMapのは、これは繰り返しません。
現在のスレッドを加えた後、キュー、そして実行に待機するacquireQueued()
方法、以下のソースコード:
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
//自旋
for (;;) {
//获取当前节点的前一个节点
final Node p = node.predecessor();
//如果前一个节点是头节点,说明当前节点排在队首,非公平锁会则再次通过tryAcquire方法获取锁
if (p == head && tryAcquire(arg)) {
//将自己设置为头节点
setHead(node);
//前一个头结点没用了,会被垃圾回收掉
p.next = null; // help GC
failed = false;
//正常结束,返回false,注意该字段可能会在下面的条件语句中被改变
return interrupted;
}
//如果前一个节点不是头节点,或者当前线程获取锁失败,会执行到这里
//shouldParkAfterFailedAcquire()方法只有在p的状态是SIGNAL时才返回false,此时parkAndCheckInterrupt()方法才有机会执行
//注意外层的自旋,for循环体会一直重试,因此只要执行到这里,总会有机会将p设置成SIGNAL状态从而将当前线程挂起
//另外,如果parkAndCheckInterrupt()返回true,说明当前线程设置了中断状态,会将interrupted设置为true,代码接着自旋,会在上一个条件语句中返回true
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
//如果在自旋中线程被中断或者发送异常,failed字段的值将会为true,这里会处理这种情况,放弃让当前线程获取锁,并抛出中断异常
if (failed)
cancelAcquire(node);
}
}
//方法逻辑是:只有在前置节点的状态是SIGNAL时才返回true,其他情况都返回false
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
return true;
//删除当前节点之前连续状态是CANCELLED的节点
if (ws > 0) {
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//线程在这里阻塞,并在被唤醒后检查中断状态
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
//
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
Node predNext = pred.next;
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
//唤醒后一个节点
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
ことを注意acquireQueued()
いずれかの割り込み例外がスローされます、または通常のエンドへの復帰がfalse
、唯一返されるスレッドの割り込みステータスを設定した後に目覚めさせられますtrue
。比較では、見つけることができますacquireQueued()
ロジックやメソッドCountDownLatch
のdoAcquireSharedInterruptibly()
多くの点で非常に類似したが、CountDownLatch
この記事では、これらのメソッドの詳細には触れませんが、このブログを通じて話しました。
かけて導入acquire()
する方法、論理的な方法に戻ります:
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
場合はtryAcquire()
、ロックを取得する方法がない場合、現在のスレッドが前のノードノードが最初のノードであるかどうかを確認するために、待ち行列最後尾に追加され、現在のスレッドは、それ以外の場合は、ハングを詰まらせるだろう、ダウン続けることができています。場合はacquireQueued
trueを返し、それを呼び出し、割り込みステータスアップスレッドセットを説明しselfInterrupt()
そうでない場合は、スレッド割り込みselfInterrupt()
方法を実行するチャンスがありません。
ロックプロセスをロックするためにここに不公平が比較的長いコードのロジックに、オーバー導入された、元のプロセスのルックは、注意を払うにコードの時間を読んで、アイデアは非常に簡単に破ることで、前後にいくつかのクラスを切り替えます。(フローチャートを構成するために必要です)。
- フェアロックロックロジック
ロジック・ロックフェアロックで見てみましょう:
final void lock() {
acquire(1);
}
非公正ロックと比較すると、ロックが公平の現れであるロジックアップロックを、つかむために公平ではありません。内のロックの他の種類のacquire()
フレームワークと同様、異なる実装の詳細と、フェアロックのを見て取るtryAcquire()
方法を:
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//c=0表示当前没有其他线程持有锁
if (c == 0) {
//下面的代码与非公平锁相比,多了hasQueuedPredecessors()方法的处理逻辑,公平锁只有在前面没有其他线程排队的情况下才会尝试获取锁
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;
}
//只要当前线程没有获取到锁,就返回false
return false;
}
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;
//h != t表示等待队列中有其他节点
//h.next == null可能会有点费解,按理说h!=t之后,h后面肯定会有节点才对,这种情况其实已经见过,在上文介绍acquireQueued()方法时说过,
//被唤醒的第一个等待节点会将自己设置为头结点,如果这个节点是队列中的唯一节点的话,它的下一个节点就是null
//至于s.thread != Thread.currentThread()这个条件暂时可以忽略,因为公平锁执行到hasQueuedPredecessors方法时根本还没有入队,
//这也意味着,只要队列中有其他节点在等候,公平锁就要求其他线程排队等待
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
lockInterruptibly
名前が示すように、lockInterruptibly
あなたは、メソッドの実装を見て、割り込みに応答することができます:
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//先尝试获取锁,获取失败才执行后面的逻辑
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
lockInterruptibly()
この方法は、ほとんどであるacquire()
唯一の違いはある、まったく同じ方法でacquire()
、この方法parkAndCheckInterrupt
のスレッドが戻るには、ステータスセットを中断しているためtrue
、単純にビット設定した場合、interrupted
フィールドの値を、そしてlockInterruptibly()
直接投げています。
unlock
方法
ロックロジックへの導入、ロジックロック解除で見てみましょう:
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
//如果成功释放了锁,则执行下面的代码块
if (tryRelease(arg)) {
Node h = head;
//如果头节点不为null,请求节点状态不是初始状态,就释放头结点后第一个有效节点
//问题:这里为什么需要判断头结点的状态呢???
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
//
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
//线程没有持有锁的情况下,不允许释放锁,否则会抛异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//可重入性的判断,如果释放了一次锁,使得c=0,就指针释放锁,做法是将记录锁的字段exclusiveOwnerThread重新指向null
//注意,只有最后一次释放可重入锁,才会返回true
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
//唤醒node节点的下一个有效节点,这里的有效指的是状态不是CANCELLED状态的节点
private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
Node s = node.next;
if (s == null || s.waitStatus > 0) {
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);
}
newCondition()
ReentrantLock
あなたが複数の待ち状態をバインドすることができ、この機能がされたnewCondition()
メソッドを実装し、それぞれの呼び出しnewCondition()
方法は、新規生成しますConditionObject
あるオブジェクト、AQS
内部クラスを、コードは非常に長いですが、ここでは詳細に説明していません。単にメソッドのソースを見てみましょう。
public Condition newCondition() {
return sync.newCondition();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
3.まとめ
マルチスレッド環境では、ReentrantLock
ロックは生産不公平なスレッドがハングオーバーヘッドコンテキスト・スイッチを避けるためにあるため、公正ロックよりも不公平なロックは、より高い性能を持っていますが、回避の飢餓への公平なスレッドロック、したがって、それぞれが独自のを持っています使用シナリオ。ビューのソースの観点から、J.U.C
パッケージには多くの種類が依存しているAQS
クラスなので、知ってもらうことが必要ですAQS
。彼は述べReentrantLock
、常に発見し、synchronized
比較しました。synchronized
またリエントラント、とにJDK 1.6
将来、synchronized
パフォーマンスが大幅に向上し、したがって、使用することを選択されたReentrantLock
一般的にその3つの利点の使用を考慮してください。割り込み、公正なロックを達成することができ、条件の数にバインドすることができ、これらの利点それはsynchronized
利用できません。