1、非公平鎖不能保證鎖的獲取是按照請(qǐng)求鎖的順序進(jìn)行的。這可能會(huì)導(dǎo)致某個(gè)或某些線程永遠(yuǎn)得不到鎖。
2、CPU喚醒線程的費(fèi)用可以降低,整體吞吐效率會(huì)很高。但是可能會(huì)有線程長時(shí)間甚至永遠(yuǎn)得不到鎖,導(dǎo)致餓死。
實(shí)例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
/** * 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 )) setExclusiveOwnerThread(Thread.currentThread()); else acquire( 1 ); } protected final boolean tryAcquire( int acquires) { return nonfairTryAcquire(acquires); } } /** * Sync object for fair locks */ 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 ; } } |
知識(shí)點(diǎn)擴(kuò)展:
非公平鎖,顧名思義,各個(gè)線程獲取到鎖的順序,不一定和它們申請(qǐng)的先后順序一致,有可能后來的線程,反而先獲取到了鎖。
在實(shí)現(xiàn)上,公平鎖在進(jìn)行l(wèi)ock時(shí),首先會(huì)進(jìn)行tryAcquire()操作。在tryAcquire中,會(huì)判斷等待隊(duì)列中是否已經(jīng)有別的線程在等待了。如果隊(duì)列中已經(jīng)有別的線程了,則tryAcquire失敗,則將自己加入隊(duì)列。如果隊(duì)列中沒有別的線程,則進(jìn)行獲取鎖的操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * 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 ; } |
非公平鎖,在進(jìn)行l(wèi)ock時(shí),會(huì)直接嘗試進(jìn)行加鎖,如果成功,則獲取到鎖,如果失敗,則進(jìn)行和公平鎖相同的動(dòng)作。
到此這篇關(guān)于java非公平鎖知識(shí)點(diǎn)實(shí)例詳解的文章就介紹到這了,更多相關(guān)java非公平鎖如何理解內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.py.cn/java/jichu/34414.html