1、非公平鎖不能保證鎖的獲取是按照請求鎖的順序進行的。這可能會導致某個或某些線程永遠得不到鎖。
2、CPU喚醒線程的費用可以降低,整體吞吐效率會很高。但是可能會有線程長時間甚至永遠得不到鎖,導致餓死。
實例
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 ; } } |
知識點擴展:
非公平鎖,顧名思義,各個線程獲取到鎖的順序,不一定和它們申請的先后順序一致,有可能后來的線程,反而先獲取到了鎖。
在實現上,公平鎖在進行lock時,首先會進行tryAcquire()操作。在tryAcquire中,會判斷等待隊列中是否已經有別的線程在等待了。如果隊列中已經有別的線程了,則tryAcquire失敗,則將自己加入隊列。如果隊列中沒有別的線程,則進行獲取鎖的操作。
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 ; } |
非公平鎖,在進行lock時,會直接嘗試進行加鎖,如果成功,則獲取到鎖,如果失敗,則進行和公平鎖相同的動作。
到此這篇關于java非公平鎖知識點實例詳解的文章就介紹到這了,更多相關java非公平鎖如何理解內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/java/jichu/34414.html