Java的LockSupport.park()實現分析(轉載)
LockSupport類是Java6(JSR166-JUC)引入的一個類,提供了基本的線程同步原語。LockSupport實際上是調用了Unsafe類裏的函數,歸結到Unsafe裏,只有兩個函數:
1 public native void unpark(Thread jthread); 2 public native void park(boolean isAbsolute, long time);
isAbsolute參數是指明時間是絕對的,還是相對的。
僅僅兩個簡單的接口,就為上層提供了強大的同步原語。
先來解析下兩個函數是做什麽的。
unpark函數為線程提供“許可(permit)”,線程調用park函數則等待“許可”。這個有點像信號量,但是這個“許可”是不能疊加的,“許可”是一次性的。
比如線程B連續調用了三次unpark函數,當線程A調用park函數就使用掉這個“許可”,如果線程A再次調用park,則進入等待狀態。
註意,unpark函數可以先於park調用。比如線程B調用unpark函數,給線程A發了一個“許可”,那麽當線程A調用park時,它發現已經有“許可”了,那麽它會馬上再繼續運行。
實際上,park函數即使沒有“許可”,有時也會無理由地返回,這點等下再解析。
park和unpark的靈活之處
上面已經提到,unpark函數可以先於park調用,這個正是它們的靈活之處。
一個線程它有可能在別的線程unPark之前,或者之後,或者同時調用了park,那麽因為park的特性,它可以不用擔心自己的park的時序問題,否則,如果park必須要在unpark之前,那麽給編程帶來很大的麻煩!!
考慮一下,兩個線程同步,要如何處理?
在Java5裏是用wait/notify/notifyAll來同步的。wait/notify機制有個很蛋疼的地方是,比如線程B要用notify通知線程A,那麽線程B要確保線程A已經在wait調用上等待了,否則線程A可能永遠都在等待。編程的時候就會很蛋疼。
另外,是調用notify,還是notifyAll?
notify只會喚醒一個線程,如果錯誤地有兩個線程在同一個對象上wait等待,那麽又悲劇了。為了安全起見,貌似只能調用notifyAll了。
park/unpark模型真正解耦了線程之間的同步,線程之間不再需要一個Object或者其它變量來存儲狀態,不再需要關心對方的狀態。
HotSpot裏park/unpark的實現
每個Java線程都有一個Parker實例,Parker類是這樣定義的:
1 class Parker : public os::PlatformParker { 2 private: 3 volatile int _counter ; 4 ... 5 public: 6 void park(bool isAbsolute, jlong time); 7 void unpark(); 8 ... 9 } 10 class PlatformParker : public CHeapObj<mtInternal> { 11 protected: 12 pthread_mutex_t _mutex [1] ; 13 pthread_cond_t _cond [1] ; 14 ... 15 }可以看到Parker類實際上用Posix的mutex,condition來實現的。
在Parker類裏的_counter字段,就是用來記錄所謂的“許可”的。
當調用park時,先嘗試直接能否直接拿到“許可”,即_counter>0時,如果成功,則把_counter設置為0,並返回:
1 void Parker::park(bool isAbsolute, jlong time) { 2 // Ideally we‘d do something useful while spinning, such 3 // as calling unpackTime(). 4 5 6 // Optional fast-path check: 7 // Return immediately if a permit is available. 8 // We depend on Atomic::xchg() having full barrier semantics 9 // since we are doing a lock-free update to _counter. 10 if (Atomic::xchg(0, &_counter) > 0) return;
如果不成功,則構造一個ThreadBlockInVM,然後檢查_counter是不是>0,如果是,則把_counter設置為0,unlock mutex並返回:
1 ThreadBlockInVM tbivm(jt); 2 if (_counter > 0) { // no wait needed 3 _counter = 0; 4 status = pthread_mutex_unlock(_mutex);
否則,再判斷等待的時間,然後再調用pthread_cond_wait函數等待,如果等待返回,則把_counter設置為0,unlock mutex並返回:
1 if (time == 0) { 2 status = pthread_cond_wait (_cond, _mutex) ; 3 } 4 _counter = 0 ; 5 status = pthread_mutex_unlock(_mutex) ; 6 assert_status(status == 0, status, "invariant") ; 7 OrderAccess::fence();當unpark時,則簡單多了,直接設置_counter為1,再unlock mutext返回。如果_counter之前的值是0,則還要調用pthread_cond_signal喚醒在park中等待的線程:
1 void Parker::unpark() { 2 int s, status ; 3 status = pthread_mutex_lock(_mutex); 4 assert (status == 0, "invariant") ; 5 s = _counter; 6 _counter = 1; 7 if (s < 1) { 8 if (WorkAroundNPTLTimedWaitHang) { 9 status = pthread_cond_signal (_cond) ; 10 assert (status == 0, "invariant") ; 11 status = pthread_mutex_unlock(_mutex); 12 assert (status == 0, "invariant") ; 13 } else { 14 status = pthread_mutex_unlock(_mutex); 15 assert (status == 0, "invariant") ; 16 status = pthread_cond_signal (_cond) ; 17 assert (status == 0, "invariant") ; 18 } 19 } else { 20 pthread_mutex_unlock(_mutex); 21 assert (status == 0, "invariant") ; 22 } 23 }
簡而言之,是用mutex和condition保護了一個_counter的變量,當park時,這個變量置為了0,當unpark時,這個變量置為1。
值得註意的是在park函數裏,調用pthread_cond_wait時,並沒有用while來判斷,所以posix condition裏的"Spurious wakeup"一樣會傳遞到上層Java的代碼裏。
關於"Spurious wakeup",參考上一篇blog:http://blog.csdn.net/hengyunabc/article/details/27969613
1 if (time == 0) { 2 status = pthread_cond_wait (_cond, _mutex) ; 3 }這也就是為什麽Java dos裏提到,當下面三種情況下park函數會返回:
- Some other thread invokes unpark with the current thread as the target; or
- Some other thread interrupts the current thread; or
- The call spuriously (that is, for no reason) returns.
相關的實現代碼在:
http://hg.openjdk.java.NET/jdk7/jdk7/hotspot/file/81d815b05abb/src/share/vm/runtime/park.hpp
http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/81d815b05abb/src/share/vm/runtime/park.cpp
http://hg.openjdk.java.Net/jdk7/jdk7/hotspot/file/81d815b05abb/src/os/Linux/vm/os_linux.hpp
http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/81d815b05abb/src/os/linux/vm/os_linux.cpp
其它的一些東東:
Parker類在分配內存時,使用了一個技巧,重載了new函數來實現了cache line對齊。
1 // We use placement-new to force ParkEvent instances to be 2 // aligned on 256-byte address boundaries. This ensures that the least 3 // significant byte of a ParkEvent address is always 0. 4 5 void * operator new (size_t sz) ;Parker裏使用了一個無鎖的隊列在分配釋放Parker實例:
1 volatile int Parker::ListLock = 0 ; 2 Parker * volatile Parker::FreeList = NULL ; 3 4 Parker * Parker::Allocate (JavaThread * t) { 5 guarantee (t != NULL, "invariant") ; 6 Parker * p ; 7 8 // Start by trying to recycle an existing but unassociated 9 // Parker from the global free list. 10 for (;;) { 11 p = FreeList ; 12 if (p == NULL) break ; 13 // 1: Detach 14 // Tantamount to p = Swap (&FreeList, NULL) 15 if (Atomic::cmpxchg_ptr (NULL, &FreeList, p) != p) { 16 continue ; 17 } 18 19 // We‘ve detached the list. The list in-hand is now 20 // local to this thread. This thread can operate on the 21 // list without risk of interference from other threads. 22 // 2: Extract -- pop the 1st element from the list. 23 Parker * List = p->FreeNext ; 24 if (List == NULL) break ; 25 for (;;) { 26 // 3: Try to reattach the residual list 27 guarantee (List != NULL, "invariant") ; 28 Parker * Arv = (Parker *) Atomic::cmpxchg_ptr (List, &FreeList, NULL) ; 29 if (Arv == NULL) break ; 30 31 // New nodes arrived. Try to detach the recent arrivals. 32 if (Atomic::cmpxchg_ptr (NULL, &FreeList, Arv) != Arv) { 33 continue ; 34 } 35 guarantee (Arv != NULL, "invariant") ; 36 // 4: Merge Arv into List 37 Parker * Tail = List ; 38 while (Tail->FreeNext != NULL) Tail = Tail->FreeNext ; 39 Tail->FreeNext = Arv ; 40 } 41 break ; 42 } 43 44 if (p != NULL) { 45 guarantee (p->AssociatedWith == NULL, "invariant") ; 46 } else { 47 // Do this the hard way -- materialize a new Parker.. 48 // In rare cases an allocating thread might detach 49 // a long list -- installing null into FreeList --and 50 // then stall. Another thread calling Allocate() would see 51 // FreeList == null and then invoke the ctor. In this case we 52 // end up with more Parkers in circulation than we need, but 53 // the race is rare and the outcome is benign. 54 // Ideally, the # of extant Parkers is equal to the 55 // maximum # of threads that existed at any one time. 56 // Because of the race mentioned above, segments of the 57 // freelist can be transiently inaccessible. At worst 58 // we may end up with the # of Parkers in circulation 59 // slightly above the ideal. 60 p = new Parker() ; 61 } 62 p->AssociatedWith = t ; // Associate p with t 63 p->FreeNext = NULL ; 64 return p ; 65 } 66 67 68 void Parker::Release (Parker * p) { 69 if (p == NULL) return ; 70 guarantee (p->AssociatedWith != NULL, "invariant") ; 71 guarantee (p->FreeNext == NULL , "invariant") ; 72 p->AssociatedWith = NULL ; 73 for (;;) { 74 // Push p onto FreeList 75 Parker * List = FreeList ; 76 p->FreeNext = List ; 77 if (Atomic::cmpxchg_ptr (p, &FreeList, List) == List) break ; 78 } 79 }
總結與扯談
JUC(java Util Concurrency)僅用簡單的park, unpark和CAS指令就實現了各種高級同步數據結構,而且效率很高,令人驚嘆。
在C++程序員各種自制輪子的時候,Java程序員則有很豐富的並發數據結構,如lock,latch,queue,map等信手拈來。
要知道像C++直到C++11才有標準的線程庫,同步原語,但離高級的並發數據結構還有很遠。boost庫有提供一些線程,同步相關的類,但也是很簡單的。Intel的tbb有一些高級的並發數據結構,但是國內boost都用得少,更別說tbb了。
最開始研究無鎖算法的是C/C++程序員,但是後來很多Java程序員,或者類庫開始自制各種高級的並發數據結構,經常可以看到有分析Java並發包的文章。反而C/C++程序員總是在分析無鎖的隊列算法。高級的並發數據結構,比如並發的HashMap,沒有看到有相關的實現或者分析的文章。在c++11之後,這種情況才有好轉。
因為正確高效實現一個Concurrent Hash Map是很困難的,要對內存CPU有深刻的認識,而且還要面對CPU不斷升級帶來的各種坑。
我認為真正值得信賴的C++並發庫,只有Intel的tbb和微軟的PPL。
https://software.intel.com/en-us/node/506042 Intel? Threading Building Blocks
http://msdn.microsoft.com/en-us/library/dd492418.aspx Parallel Patterns Library (PPL)
另外FaceBook也開源了一個C++的類庫,裏面也有並發數據結構。
https://github.com/facebook/folly
全文轉載自:Java的LockSupport.park()實現分析
Java的LockSupport.park()實現分析(轉載)