<b>synchronized:</b>把代碼塊聲明為 synchronized,有兩個(gè)重要后果瞪浸,通常是指該代碼具有 原子性(atomicity)和 可見(jiàn)性(visibility)漓糙。原子性意味著一個(gè)線程一次只能執(zhí)行由一個(gè)指定監(jiān)控對(duì)象(lock)保護(hù)的代碼潦匈,從而防止多個(gè)線程在更新共享狀態(tài)時(shí)相互沖突闹丐『崤梗可見(jiàn)性表示每次都從內(nèi)存中拿去最新的值,以及代碼塊結(jié)束之前將最新的值更新到內(nèi)存
<b>ReentrantLock:</b>相對(duì)于synchronized添加了類(lèi)似鎖投票卿拴、定時(shí)鎖等候和可中斷鎖等候的一些特性衫仑。此外,它還提供了在激烈爭(zhēng)用情況下更佳的性能堕花。(換句話說(shuō)文狱,當(dāng)許多線程都想訪問(wèn)共享資源時(shí),JVM 可以花更少的時(shí)候來(lái)調(diào)度線程缘挽,把更多時(shí)間用在執(zhí)行線程上如贷。)
之前也就是拿ReentrantLock來(lái)用用或者主要還是用synchronized比較多陷虎,還是想擼擼ReentrantLock的源代碼:
<b>uml 類(lèi)圖梳理:</b>
<pre>
</pre>
<b>Sync類(lèi):</b>
<pre>
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/*
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
/
abstract void lock(); //抽象方法被公平鎖和非公平鎖分別實(shí)現(xiàn)
/*
* Performs non-fair tryLock. tryAcquire is
* implemented in subclasses, but both need nonfair
* try for trylock method.
*/
final boolean nonfairTryAcquire(int acquires) { //嘗試獲取非公平鎖
final Thread current = Thread.currentThread();
int c = getState(); //獲取基類(lèi)AbstractQueuedSynchronizer的 volatile state屬性
if (c == 0) { //表示空閑狀態(tài)
if (compareAndSetState(0, acquires)) { // 使用了sun.misc下面的UnSafe類(lèi)的compareAndSwapInt方法到踏,跟AtomicInteger等原子性類(lèi)實(shí)現(xiàn)一樣
setExclusiveOwnerThread(current); //設(shè)置鎖被占用的線程為當(dāng)前線程
return true;
}
}
else if (current == getExclusiveOwnerThread()) { //如果鎖已經(jīng)被當(dāng)前線程使用杠袱,重用鎖
int nextc = c + acquires; //在原有的鎖上面使state的值變大,所以如果釋放鎖的話需要使state直到變成0窝稿,單純減1沒(méi)有釋放鎖
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; //使得state值變小
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() { //其實(shí)上面的判斷可用改成直接調(diào)用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() { //獲取鎖被入次數(shù),因?yàn)榫€程可以重入鎖
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 {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
</pre>
<b>UnSafe.compareAndSwapInt補(bǔ)充:</b>CAS是項(xiàng)樂(lè)觀鎖技術(shù)楣富,當(dāng)多個(gè)線程嘗試使用CAS同時(shí)更新同一個(gè)變量時(shí),只有其中一個(gè)線程能更新變量的值伴榔,而其它線程都失敗纹蝴,失敗的線程并不會(huì)被掛起,而是被告知這次競(jìng)爭(zhēng)中失敗踪少,并可以再次嘗試塘安。CAS有3個(gè)操作數(shù),內(nèi)存值V援奢,舊的預(yù)期值A(chǔ)兼犯,要修改的新值B。當(dāng)且僅當(dāng)預(yù)期值A(chǔ)和內(nèi)存值V相同時(shí)集漾,將內(nèi)存值V修改為B切黔,否則什么都不做。
<b>NonfairSync類(lèi):</b>
<pre>
/**
* Sync object for non-fair locks
*/
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)) //這是跟公平鎖的主要區(qū)別具篇,一上來(lái)就試探鎖是否空閑纬霞,可以插隊(duì)
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1); //具體實(shí)現(xiàn)看如下
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
AbstractQueuedSynchronizer類(lèi)的acquire實(shí)現(xiàn):
public final void acquire(int arg) {
if (!tryAcquire(arg) && //嘗試獲取鎖
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //如果獲取鎖失敗則丟到鎖等待的隊(duì)列中
selfInterrupt();
}
/**
* 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 = 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); //其實(shí)這個(gè)主要是處理當(dāng)pred == null 時(shí)處理兩步 1、新建head 且 tail = head 2驱显、tail = node 里面是個(gè)循環(huán)操作诗芜,不為空時(shí)只處理第二步,我看了一下enq這個(gè)方法有好幾處在用所以作者把它包裝起來(lái)
return node;
}
<b>雙向鏈表圖:</b>
<b>acquireQueued源碼:</b>
/*
* 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) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) { //循環(huán):如果獲取到鎖則結(jié)束埃疫,如果前面還有節(jié)點(diǎn)則等待前面節(jié)點(diǎn)獲取鎖結(jié)束以后釋放信號(hào)
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) && 判斷后續(xù)線程是否應(yīng)該被阻塞伏恐,這里的p的后續(xù)線程其實(shí)就是當(dāng)前線程
parkAndCheckInterrupt()) //里面 LockSupport.park(this);阻塞當(dāng)前線程,以及檢測(cè)是否被中斷
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//shouldParkAfterFailedAcquire
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL) //CANCELLED[1]:當(dāng)前線程已被取消
SIGNAL[-1]:后繼節(jié)點(diǎn)將被或者已經(jīng)被阻塞,所以當(dāng)前節(jié)點(diǎn)在釋放或者取消時(shí),需要unpark它的后繼節(jié)點(diǎn)帮孔。
CONDITION[-2]:當(dāng)前線程(處在Condition休眠狀態(tài))在等待Condition喚醒
PROPAGATE[-3]:(共享鎖)其它線程獲取到“共享鎖”
/
* This node has already set status asking a release
* to signal it, so it can safely park.
/
return true;
if (ws > 0) {
/
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
/
do {
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.
/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
</pre>
<b>FairSync類(lèi)源碼:</b>
<pre>
/*
* Sync object for fair locks
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() { //相對(duì)于NonfairSync的lock少了一來(lái)就compareAndSetState(0, 1)空閑就上鎖
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() && //相對(duì)于NonfairSync的tryAcquire就是多了一個(gè)先判斷等待隊(duì)列中是否有其它等待的線程
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;
}
}
</pre>
<b>NonfairSync 和 FairSync比較分析:</b>非公平鎖來(lái)了先判斷是否空閑烫堤,空閑就占用鎖,公平鎖先查看等待隊(duì)列中是否有其它線程等待恒傻,按序獲取鎖不能插隊(duì)。可想而知非公平鎖效率更高闻鉴,但是公平鎖也有其特定的使用場(chǎng)景。new ReentrantLock() 默認(rèn)是指定的非公平鎖也相當(dāng)于new ReentrantLock(false) 表示調(diào)用NonfairSync 的非公平鎖,new ReentrantLock(true) 表示調(diào)用 FairSync的公平鎖
<b>ReentrantLock如何響應(yīng)鎖中斷茂洒?</b>
先說(shuō)說(shuō)線程的打擾機(jī)制孟岛,每個(gè)線程都有一個(gè) 打擾 標(biāo)志。
這里分兩種情況:
線程在sleep或wait,join, 此時(shí)如果別的線程調(diào)用此線程的 interrupt()方法渠羞,此線程會(huì)被喚醒并被要求處理InterruptedException
-
此線程在運(yùn)行中斤贰, 則不會(huì)收到提醒。但是 此線程的 “打擾標(biāo)志”會(huì)被設(shè)置次询, 可以通過(guò)isInterrupted()查看并 作出處理
lockInterruptibly()和上面的第一種情況是一樣的荧恍, 線程在請(qǐng)求lock并被阻塞時(shí),如果被interrupt屯吊,則此線程會(huì)被喚醒并拋出InterruptedException
上個(gè)例子:
<pre>
public class Test {
public static void test() throws Exception {
final Lock lock = new ReentrantLock();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
}
});
t1.start();
t1.interrupt();
Thread.sleep(10000000);
}public static void main(String[] args) throws Exception {
Test.test();
}
}
輸出結(jié)果為:
Thread-0 interrupted.
</pre>
<pre>
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
基類(lèi)代碼:
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
doAcquireInterruptibly的實(shí)現(xiàn)跟acquireQueued實(shí)現(xiàn)有些類(lèi)似送巡。
doAcquireInterruptibly以 throw new InterruptedException()來(lái)中斷
acquireQueued 即使檢測(cè)到了Thread.interruptted為true一樣會(huì)繼續(xù)嘗試獲取鎖,失敗則繼續(xù)等待只是在最后獲取鎖成功之后在把當(dāng)前線程置為 interrupted = true狀態(tài)盒卸。
</pre>