• Java的LockSupport.park()实现分析


    LockSupport类是Java6(JSR166-JUC)引入的一个类,提供了基本的线程同步原语。LockSupport实际上是调用了Unsafe类里的函数,归结到Unsafe里,只有两个函数:

     park:阻塞当前线程(Block current thread),字面理解park,就算占住,停车的时候不就把这个车位给占住了么?起这个名字还是很形象的。

    unpark: 使给定的线程停止阻塞(Unblock the given thread blocked )。

     
    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类是这样定义的:

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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,并返回:

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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并返回:

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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并返回:

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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中等待的线程:

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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

    [cpp] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/share/vm/runtime/park.hpp
    http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/share/vm/runtime/park.cpp
    http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/os/linux/vm/os_linux.hpp
    http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/os/linux/vm/os_linux.cpp  

    其它的一些东东:

    Parker类在分配内存时,使用了一个技巧,重载了new函数来实现了cache line对齐。

    [cpp] view plaincopy
     
    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实例:

    [cpp] view plaincopy
     
    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指令就实现了各种高级同步数据结构,而且效率很高,令人惊叹。

  • 相关阅读:
    Android轩辕剑之ActionBar之三
    Android轩辕剑之ActionBar之二
    Android轩辕剑之ActionBar之一
    使用Android OpenGL ES 2.0绘图之六:响应触摸事件
    使用Android OpenGL ES 2.0绘图之五:添加运动
    使用Android OpenGL ES 2.0绘图之四:应用投影和相机视口
    使用Android OpenGL ES 2.0绘图之三:绘制形状
    使用Android OpenGL ES 2.0绘图之二:定义形状
    随笔编号-16 MySQL查看表及索引大小方法
    随笔编号-14 数据库连接最大数问题
  • 原文地址:https://www.cnblogs.com/bendantuohai/p/4653543.html
Copyright © 2020-2023  润新知