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

转载于:https://www.cnblogs.com/bendantuohai/p/4653543.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/290875.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Android之用adb screencap -p命令截图

1、截图保存到sdcard adb shell /system/bin/screencap -p /sdcard/screenshot.png 2、pull拉取到本地 adb pull /sdcard/screenshot.png

Avalonia跨平台入门第二篇

前面一篇简单的弄了个Demo去玩耍了一下Avalonia;你还别说效还挺有意思,这不咱们今天接着更深一步的去了解他,来看看效果:在统信UOS下运行效果:环境搭建在统信UOS(多一步开启开发模式):使用开源的PanAndZoom控件&#xff1a;继承Canvas自定义控件,进行网格绘制&#xff1a;最终简…

耶鲁大学计算机科学录取,2020年耶鲁大学排名TFE Times美国最佳计算机科学硕士专业排名第18...

耶鲁大学实力介绍耶鲁大学(Yale University)&#xff0c;简称“耶鲁(Yale)”&#xff0c;是一所坐落于美国康涅狄格州纽黑文的世界著名私立研究型大学&#xff0c;是八所常春藤盟校中最重视本科教育的大学之一。耶鲁大学有3,200名教职工&#xff0c;每年招收约1,250名学生&…

[九]RabbitMQ-客户端源码之Consumer

在[八]RabbitMQ-客户端源码之ChannelN中讲述basicConsume的方法时设计到Consumer这个回调函数&#xff0c;Consumer其实是一个接口&#xff0c;真正实现它的是QueueingConsumer和DefaultConsumer&#xff0c;且DefaultConsumer是QueueingConsumer的父类&#xff0c;里面都是空方…

Performance Metrics(性能指标1)

Performance Metrics(性能指标) 在我们开始旅行本书之前&#xff0c;我必须先了解本书的性能指标和希望优化后的结果&#xff0c;在第二章中&#xff0c;我们探索更多的性能检测工具和性能指标&#xff0c;可是&#xff0c;您得会使用这些工具和明白这些性能指标的意义。 由于业…

ExtJs 4.x Ajax简单封装

/*** Ajax 请求*/ Ext.define("SinoCloudAjaxRequestClass", {constructor : function () {var me this;var viewport me.getViewPort();if(viewport){window.sinoCloudAjaxRequestClassLoadingMak new Ext.LoadMask(viewport, {msg:"处理中..."});}},r…

可能是.NET领域性能最好的对象映射框架——Mapster

我之前文章提到过 MediatR 的作者 Jimmy Bogard&#xff0c;他也是大名鼎鼎的对象映射框架 AutoMapper 的作者。AutoMapper 的功能强大&#xff0c;在 .NET 领域的开发者中有非常高的知名度和使用率。而今天老衣要提的是另外一款高性能对象映射框架&#xff1a;Mapster——它轻…

Android studio之Unknown run configuration type AndroidRunConfigurationType解决办法

1、问题 我也就是只是一开始点击了File->invalidate cachas / restart -> invalidate and restart 在Android studio里面运行之前正常的安卓项目&#xff0c;报下错误Unknown run configuration type AndroidRunConfigurationTyp 2、解决办法 原因&#xff1a;是因为插件…

Delphi XE5实现减少编译出来的程序体积

本文章介绍了Delphi XE5实现减少编译出来的程序体积&#xff0c;一般情况下&#xff0c;编译出来的文件会比较大&#xff0c;对于发布来说&#xff0c;比较不方便&#xff0c;经过查询&#xff0c;找到了两个减少体积的办法1&#xff1a;关闭DEBUG信息&#xff0c;通过下面的步…

超级计算机适用于科学计算,中国科学院

中科院合肥物质科学研究院物质科学计算中心超算用户使用规章为加强物质科学计算中心(中科院超级计算环境合肥分中心)的运行管理&#xff0c;合理和科学地使用超算资源&#xff0c;发挥超算平台在科研工作中的作用&#xff0c;特制订此规章。1. 用户应自觉遵守国家的各项法律规定…

[cocos2d]修改富文本文本和高度

1.local richTable { {text , color cc.c3b(173,118,15)}, {custom , color ItemMacro[index].color, param id} } 2.item:setContentSize(50,20)转载于:https://www.cnblogs.com/Faiz-room/p/6727072.html

CodeForces 546B

题目链接&#xff1a;http://acm.hust.edu.cn/vjudge/contest/view.action?cid82659#problem/C 解题思路&#xff1a;先对输入的数据放入a数组里面存储&#xff0c;再将a数组用sort进行排序&#xff0c;从第二个数开始判断&#xff0c;是否比第一个大&#xff0c;如果大&#…

Avalonia跨平台入门第一篇

作为一枚屌丝程序员来说最大的爱好就是撸代码,有时候根本停不下来(沉迷工作,无法自拔);因为一直都是WPF开发,后面也摸索了一下Xamarin的东西;这不又看到其他人又在搞什么跨平台;我也是手也很痒痒;就像刚开始摸索Xamarin一样,想又不知如何下手;这不再次迈出了第一步去摸索Avalon…

linux之用route命令看简单路由信息

1、我们在linux上简单看路由信息使用下面命令 route -n

三角形带优化库nvtrisrip的使用

nvtrisrip是NVIDIA提供的一个开源优化库&#xff0c;这个库可以将三角形顶点索引数组转换为三角形带索引数组。可以极大的提高渲染速度。NVIDIA这个库的官方地址是&#xff1a;http://www.nvidia.com/object/nvtristrip_library.html不过这里代码不全也不够新&#xff0c;推荐从…

angular-ui-tab-scroll

2019独角兽企业重金招聘Python工程师标准>>> A scrollable tab plugin intended for scrolling UI Bootstrap tabset. 功能介绍&#xff1a;http://npm.taobao.org/package/angular-ui-tab-scroll 下载地址&#xff1a;https://github.com/VersifitTechnologies/ang…

调用带有 out 参数的方法时检查弃元参数

前言C# 支持弃元&#xff0c;弃元是应用程序代码中故意未使用的占位符变量。弃元将意图传达给编译器和读取代码的其他人&#xff1a;你打算忽略表达式的结果。通过为变量分配下划线(_)作为其名称&#xff0c;可以指示变量是弃元变量。例如下列代码&#xff1a;if (DateTime.Try…

007-网站的搭建

昨天在极客学院的视频引导下&#xff0c;我成功的模拟量本地建站和利用虚拟主机建站。 我用的虚拟主机是阿里云提供的虚拟主机&#xff0c;域名是从万网购买的&#xff0c;网站模板是wordpress。 先通过虚拟主机把网站搭建好&#xff0c;再买域名&#xff0c;将域名解析到网站上…

潍坊学院计算机系崔玲玲,人工免疫算法在引水工程中的应用.pdf

人工免疫算法在引水工程中的应用.pdf第 14卷第2期 潍坊学院学报 Vo1&#xff0e;14No&#xff0e;22014年 4月 JournalofWeifangUniversity Apr&#xff0e;2014人工免疫算法在引水工程中的应用崔玲玲 &#xff0c;王林叶 &#xff0c;陈志银(1-潍坊学院&#xff0c;山东 潍坊 …

Android之Unable to execute dex: Multiple dex files define 解决方法

1、问题 运行Android项目&#xff0c;出现Unable to execute dex: Multiple dex files define 这个错误 2、原因 代码里面引用的jar包和项目里面的类冲突了&#xff0c;一般比如&#xff0c;我写了这个项目&#xff0c;然后把这个项目打成jar包&#xff0c;然后再导入这个项目…