4.锁定--Java的LockSupport.park()实现分析

LockSupport类是Java6(JSR166-JUC)引入的一个类,提供了主要的线程同步原语。

LockSupport实际上是调用了Unsafe类里的函数。归结到Unsafe里,仅仅有两个函数:

[java] view
plain
copy

  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
plain
copy

  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
plain
copy

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

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

[cpp] view
plain
copy

  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
plain
copy

  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
plain
copy

  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
plain
copy

  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
plain
copy

  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. void * operator new (size_t sz) ;

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

[cpp] view
plain
copy

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

总结与扯谈

JUC(Java Util Concurrency)仅用简单的park, unpark和CAS指令就实现了各种高级同步数据结构,并且效率非常高,令人惊叹。

在C++程序猿各种自制轮子的时候,Java程序猿则有非常丰富的并发数据结构,如lock,latch,queue,map等信手拈来。

要知道像C++直到C++11才有标准的线程库,同步原语,但离高级的并发数据结构还有非常远。boost库有提供一些线程,同步相关的类,但也是非常easy的。

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

版权声明:本文博主原创文章,博客,未经同意不得转载。

时间: 2024-08-06 21:05:48

4.锁定--Java的LockSupport.park()实现分析的相关文章

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参数是指明时间是绝对的,还是相对的. 仅仅两个简单的接口,就为上层提供了强大

Java的LockSupport.park()实现分析

LockSupport类是Java6(JSR166-JUC)引入的一个类,提供了基本的线程同步原语.LockSupport实际上是调用了Unsafe类里的函数,归结到Unsafe里,只有两个函数: [java] view plaincopy public native void unpark(Thread jthread); public native void park(boolean isAbsolute, long time); isAbsolute参数是指明时间是绝对的,还是相对的. 仅

Java线程池使用和分析(二) - execute()原理

相关文章目录: Java线程池使用和分析(一) Java线程池使用和分析(二) - execute()原理 execute()是 java.util.concurrent.Executor接口中唯一的方法,JDK注释中的描述是“在未来的某一时刻执行命令command”,即向线程池中提交任务,在未来某个时刻执行,提交的任务必须实现Runnable接口,该提交方式不能获取返回值.下面是对execute()方法内部原理的分析,分析前先简单介绍线程池有哪些状态,在一系列执行过程中涉及线程池状态相关的判断

java自带的jvm分析工具

http://domark.iteye.com/blog/1924302 这段时间觉得很有必要对java的内存分析工具进行熟悉,这样以后出现机器负载较高,或者反应很慢的时候,我就可以查找原因了.上网搜了搜,发现下面这些是比较常用的,然后我在机器上试试了,把结果也贴出来哈. 1.jps 类似ps -ef|grep java 显示java进程号 或者pgrep java2.jstack 打印jvm内存的堆栈信息,打印出来的结果类似 2010-04-21 20:10:51 Full thread du

JAVA并发--LockSupport

LockSupport概览 Basic thread blocking primitives for creating locks and other synchronization classes.用来创建锁及其他同步类的基础线程阻塞原语.这是java doc中的解释,以下是一个先进先出 (first-in-first-out) 非重入锁类的框架. * class FIFOMutex { * private final AtomicBoolean locked = new AtomicBool

面试 LockSupport.park()会释放锁资源吗?

(手机横屏看源码更方便) 引子 大家知道,我最近在招人,今天遇到个同学,他的源码看过一些,然后我就开始了AQS连环问. 我:说说AQS的大致流程? 他:AQS包含一个状态变量,一个同步队列--balabala--互斥锁balabala,共享锁balabala-- 我:AQS中除了同步队列,还有什么队列? 他:还有个Condition,Condition中有个条件队列-- 我:条件队列和同步队列有什么区别? 他:条件队列balabala,然后调用LockSupport.park()进入休眠,等待被

LockSupport源码分析

目录 LockSupport源码分析 LockSupport的实现 1. 内部重要的属性: 2. getBlocker(Thread) 与 setBlocker(Thread t, Object arg)源码 3. park的其他几个方法 4. park()/unpark() 与 wait()/notify()区别: LockSupport源码分析 LockSupport是Java6引入的一个工具类, 用于挂起和唤醒线程; LockSupport 通过提供park() 和 unpark() 方法

java并发LockSupport

java并发LockSupport LockSupport是阻塞和唤醒线程的重要类. park()方法使得当前线程阻塞 unpark(Thread thread)唤醒线程 例子 可以把注释取消再执行,就会发现park()方法使得当前线程阻塞会使得main线程阻塞,无法结束. package com.java.javabase.thread.base.concurrent.lock; import lombok.extern.slf4j.Slf4j; import java.util.concur

java.io.BufferedOutputStream 源码分析

BufferedOutputStream  是一个带缓冲区到输出流,通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统. 俩个成员变量,一个是存储数据的内部缓冲区,一个是缓冲区中的有效字节数. /** * The internal buffer where data is stored. */ protected byte buf[]; /** * The number of valid bytes in the buffer. This value