java 线程同步原语: LockSupport

LockSupport类是Java6(JSR166-JUC)引入的一个类,提供了基本的线程阻塞原语,基于lockSupport 实现了很多场景类的工具类,比如Lock ,CountDownLatch,BlockingQueue等

这个类的作用就是阻塞线程,解阻塞线程,依赖于这个功能,我们可以做出好多场景实现,

比如在获取某个锁的时候,获取不到我就要阻塞线程,

比如向队列里添加元素的时候,如果添加失败,就阻塞或者从队列里获取元素,如果获取不到就阻塞。

比如一个线程阻塞 一直等待其他线程都执行完之后才执行。

比如 有20个线程,想要等到所有线程都阻塞一直等到某个事件才开始继续执行。等等。

 

以下是函数列表:

// 返回提供给最近一次尚未解除阻塞的 park 方法调用的 blocker 对象,如果该调用不受阻塞,则返回 null。
static Object getBlocker(Thread t)
// 为了线程调度,禁用当前线程,除非许可可用。
static void park()
// 为了线程调度,在许可可用之前禁用当前线程。
static void park(Object blocker)
// 为了线程调度禁用当前线程,最多等待指定的等待时间,除非许可可用。
static void parkNanos(long nanos)
// 为了线程调度,在许可可用前禁用当前线程,并最多等待指定的等待时间。
static void parkNanos(Object blocker, long nanos)
// 为了线程调度,在指定的时限前禁用当前线程,除非许可可用。
static void parkUntil(long deadline)
// 为了线程调度,在指定的时限前禁用当前线程,除非许可可用。
static void parkUntil(Object blocker, long deadline)
// 如果给定线程的许可尚不可用,则使其可用。
static void unpark(Thread thread)

 

LockSupport是通过调用Unsafe函数中的接口实现阻塞和解除阻塞的 ,归结到Unsafe里,只有两个函数:

public native void unpark(Thread jthread);   //解锁阻塞的线程,使得线程继续执行。

public native void park(boolean isAbsolute, long time);   // 阻塞线程继续执行,isAbsolute参数是指明时间是绝对的,还是相对的。

LockSupport park 实现:

public static void park(Object blocker) {//blocker是一个lock
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    unsafe.park(false, 0L);
    setBlocker(t, null);
}

 

注意:

unpark函数为线程提供“许可(permit)”,线程调用park函数则等待“许可”。这个有点像信号量,但是这个“许可”是不能叠加的,“许可”是一次性的。比如线程B连续调用了三次unpark函数,当线程A调用park函数就使用掉这个“许可”,如果线程A再次调用park,则进入等待状态。

unpark函数可以先于park调用。比如线程B调用unpark函数,给线程A发了一个“许可”,那么当线程A调用park时,它发现已经有“许可”了,那么它会马上再继续运行

park和wait的区别: wait让线程阻塞前,必须通过synchronized获取同步锁

实际上,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,并返回:void Parker::park(bool isAbsolute, jlong time) {  

  1.   // Ideally we'd do something useful while spinning, such  
  2.   // as calling unpackTime().  
  3.   
  4.   
  5.   // Optional fast-path check:  
  6.   // Return immediately if a permit is available.  
  7.   // We depend on Atomic::xchg() having full barrier semantics  
  8.   // since we are doing a lock-free update to _counter.  
  9.   if (Atomic::xchg(0, &_counter) > 0) return;  

如果不成功,则构造一个ThreadBlockInVM,然后检查_counter是不是>0,如果是,则把_counter设置为0,unlock mutex并返回:

     ThreadBlockInVM tbivm(jt);  

  1. if (_counter > 0)  { // no wait needed  
  2.   _counter = 0;  
  3.   status = pthread_mutex_unlock(_mutex);  

否则,再判断等待的时间,然后再调用pthread_cond_wait函数等待,如果等待返回,则把_counter设置为0,unlock mutex并返回:        if (time == 0) {  

  1.   status = pthread_cond_wait (_cond, _mutex) ;  
  2. }  
  3. _counter = 0 ;  
  4. status = pthread_mutex_unlock(_mutex) ;  
  5. assert_status(status == 0, status, "invariant") ;  
  6. 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的代码里。

if (time == 0) {  

  1.   status = pthread_cond_wait (_cond, _mutex) ;  
  2. }  

 

这也就是为什么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对齐。

// We use placement-new to force ParkEvent instances to be  

  1. // aligned on 256-byte address boundaries.  This ensures that the least  
  2. // significant byte of a ParkEvent address is always 0.  
  3.    
  4. void * operator new (size_t sz) ;  

Parker里使用了一个无锁的队列在分配释放Parker实例:

volatile int Parker::ListLock = 0 ;  

  1. Parker * volatile Parker::FreeList = NULL ;  
  2.   
  3. Parker * Parker::Allocate (JavaThread * t) {  
  4.   guarantee (t != NULL, "invariant") ;  
  5.   Parker * p ;  
  6.   
  7.   // Start by trying to recycle an existing but unassociated  
  8.   // Parker from the global free list.  
  9.   for (;;) {  
  10.     p = FreeList ;  
  11.     if (p  == NULL) break ;  
  12.     // 1: Detach  
  13.     // Tantamount to p = Swap (&FreeList, NULL)  
  14.     if (Atomic::cmpxchg_ptr (NULL, &FreeList, p) != p) {  
  15.        continue ;  
  16.     }  
  17.   
  18.     // We've detached the list.  The list in-hand is now  
  19.     // local to this thread.   This thread can operate on the  
  20.     // list without risk of interference from other threads.  
  21.     // 2: Extract -- pop the 1st element from the list.  
  22.     Parker * List = p->FreeNext ;  
  23.     if (List == NULL) break ;  
  24.     for (;;) {  
  25.         // 3: Try to reattach the residual list  
  26.         guarantee (List != NULL, "invariant") ;  
  27.         Parker * Arv =  (Parker *) Atomic::cmpxchg_ptr (List, &FreeList, NULL) ;  
  28.         if (Arv == NULL) break ;  
  29.   
  30.         // New nodes arrived.  Try to detach the recent arrivals.  
  31.         if (Atomic::cmpxchg_ptr (NULL, &FreeList, Arv) != Arv) {  
  32.             continue ;  
  33.         }  
  34.         guarantee (Arv != NULL, "invariant") ;  
  35.         // 4: Merge Arv into List  
  36.         Parker * Tail = List ;  
  37.         while (Tail->FreeNext != NULL) Tail = Tail->FreeNext ;  
  38.         Tail->FreeNext = Arv ;  
  39.     }  
  40.     break ;  
  41.   }  
  42.   
  43.   if (p != NULL) {  
  44.     guarantee (p->AssociatedWith == NULL, "invariant") ;  
  45.   } else {  
  46.     // Do this the hard way -- materialize a new Parker..  
  47.     // In rare cases an allocating thread might detach  
  48.     // a long list -- installing null into FreeList --and  
  49.     // then stall.  Another thread calling Allocate() would see  
  50.     // FreeList == null and then invoke the ctor.  In this case we  
  51.     // end up with more Parkers in circulation than we need, but  
  52.     // the race is rare and the outcome is benign.  
  53.     // Ideally, the # of extant Parkers is equal to the  
  54.     // maximum # of threads that existed at any one time.  
  55.     // Because of the race mentioned above, segments of the  
  56.     // freelist can be transiently inaccessible.  At worst  
  57.     // we may end up with the # of Parkers in circulation  
  58.     // slightly above the ideal.  
  59.     p = new Parker() ;  
  60.   }  
  61.   p->AssociatedWith = t ;          // Associate p with t  
  62.   p->FreeNext       = NULL ;  
  63.   return p ;  
  64. }  
  65.   
  66.   
  67. void Parker::Release (Parker * p) {  
  68.   if (p == NULL) return ;  
  69.   guarantee (p->AssociatedWith != NULL, "invariant") ;  
  70.   guarantee (p->FreeNext == NULL      , "invariant") ;  
  71.   p->AssociatedWith = NULL ;  
  72.   for (;;) {  
  73.     // Push p onto FreeList  
  74.     Parker * List = FreeList ;  
  75.     p->FreeNext = List ;  
  76.     if (Atomic::cmpxchg_ptr (p, &FreeList, List) == List) break ;  
  77.   }  
  78. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值