Implementation Analysis of LockSupport. park () in Java

Source: Internet
Author: User

The LockSupport class is a class introduced by Java 6 (JSR166-JUC) and provides basic thread synchronization primitives. LockSupport actually calls the functions in the Unsafe class. It comes down to Unsafe, and there are only two functions:

  public native void unpark(Thread jthread);  public native void park(boolean isAbsolute, long time);

The isAbsolute parameter specifies whether the time is absolute or relative.

Only two simple interfaces provide powerful synchronization primitives for the upper layer.

Let's first parse what two functions do.

The unpark function provides a "permit" for the thread. The thread calls the park function and waits for the "permission ". This is a bit like a semaphore, but this "License" cannot be superimposed. "License" is a one-time license.

For example, thread B calls the unpark function three times in A row. When thread A calls the park function, this "License" is used. If thread A calls the park function again, it enters the waiting state.

Note that the unpark function can be called before the park function. For example, if thread B calls the unpark function and sends A "License" to thread A, when thread A calls the park, it finds that there is A "License, then it will continue running immediately.

In fact, even if the park function does not have a "License", sometimes it will return with no reason. This will be resolved later.

Flexibility of park and unpark

As mentioned above, unpark functions can be called before park, which is exactly what they are flexible.

A thread may be before or after another thread unPark, or call park at the same time. Because of the characteristics of park, it does not have to worry about the timing of its own park. Otherwise, if the park must be before unpark, it will bring a lot of trouble to programming !!

What should I do if two threads are synchronized?

In Java 5, wait/notify/notifyAll is used for synchronization. The wait/notify mechanism has a pain point, for exampleThread B must notify thread A with notify, so thread B must ensure that thread A has waited for the wait call; otherwise, thread A may always be waiting.Programming can be very painful.

In addition,Does it call policy or policyall?

Notify will only wake up one thread. If two threads are mistakenly waiting for wait on the same object, it will be a tragedy. For the sake of security, it seems that only policyall can be called.

The park/unpark model truly decouples the synchronization between threads. One Object or other variables are no longer needed between threads to store the state, and the other party's state is no longer required.


Implementation of park/unpark in HotSpot

Each java thread has a Parker instance, which is defined as follows:

class Parker : public os::PlatformParker {private:  volatile int _counter ;  ...public:  void park(bool isAbsolute, jlong time);  void unpark();  ...}class PlatformParker : public CHeapObj
 
   {  protected:    pthread_mutex_t _mutex [1] ;    pthread_cond_t  _cond  [1] ;    ...}
 
We can see that the Parker class is actually implemented using the mutex and condition of Posix.

The _ counter field in the Parker class is used to record the so-called "License.

When calling park, first try to directly get the "License", that is, if _ counter> 0, if it is successful, SET _ counter to 0, and return:

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

If not, construct a ThreadBlockInVM and check whether _ counter is greater than 0. If yes, SET _ counter to 0, unlock mutex, and return:

  ThreadBlockInVM tbivm(jt);  if (_counter > 0)  { // no wait needed    _counter = 0;    status = pthread_mutex_unlock(_mutex);

Otherwise, judge the waiting time and call the pthread_cond_wait function. If the wait time is returned, SET _ counter to 0, unlock mutex, and return:

  if (time == 0) {    status = pthread_cond_wait (_cond, _mutex) ;  }  _counter = 0 ;  status = pthread_mutex_unlock(_mutex) ;  assert_status(status == 0, status, "invariant") ;  OrderAccess::fence();
When unpark is used, it is much simpler. directly set _ counter to 1, and then unlock mutext to return. If the value before _ counter is 0, you also need to call pthread_cond_signal to wake up the thread waiting in the park:

void Parker::unpark() {  int s, status ;  status = pthread_mutex_lock(_mutex);  assert (status == 0, "invariant") ;  s = _counter;  _counter = 1;  if (s < 1) {     if (WorkAroundNPTLTimedWaitHang) {        status = pthread_cond_signal (_cond) ;        assert (status == 0, "invariant") ;        status = pthread_mutex_unlock(_mutex);        assert (status == 0, "invariant") ;     } else {        status = pthread_mutex_unlock(_mutex);        assert (status == 0, "invariant") ;        status = pthread_cond_signal (_cond) ;        assert (status == 0, "invariant") ;     }  } else {    pthread_mutex_unlock(_mutex);    assert (status == 0, "invariant") ;  }}
In short, mutex and condition are used to protect a _ counter variable. When the park is used, this variable is set to 0, and when the unpark is used, this variable is set to 1.
It is worth noting that in the park function, when pthread_cond_wait is called, it is not judged by the while. Therefore, the "Spurious wakeup" in posix condition will be passed to the upper-layer Java code.

For "Spurious wakeup", refer to the previous blog: http://blog.csdn.net/hengyunabc/article/details/27969613

  if (time == 0) {    status = pthread_cond_wait (_cond, _mutex) ;  }

This is why the park function will return the following three conditions as mentioned in Java dos:

Some other thread invokes unpark with the current thread as the target; orSome other thread interrupts the current thread; or The call spuriously (that is, for no reason) returns.

The related implementation code is as follows:

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

Conclusion and discussion

JUC (Java Util Concurrency) only uses simple parks. The unpark and CAS commands implement various advanced synchronization data structures, which are highly efficient and amazing.

When C ++ programmers make various self-made wheels, Java programmers have a wealth of concurrent data structures, such as lock, latch, queue, and map.

You need to know that C ++ has a standard thread library and a synchronization primitive until C ++ 11, but it is still far from the advanced concurrent data structure. The boost Library provides some threads and synchronization-related classes, but it is also very simple. Intel's tbb has some advanced concurrent data structures, but it uses less boost in China, let alone tbb.

C/C ++ programmers started to study lockless algorithms. However, many Java programmers or class libraries began to develop various advanced concurrent data structures, I often see articles that analyze Java and send packets. Instead, C/C ++ programmers are always analyzing lock-free queue algorithms. Advanced concurrent data structures, such as concurrent HashMap, do not see any related implementation or analysis articles. After C ++ 11, this situation has improved.

It is very difficult to implement a Concurrent Hash Map correctly and efficiently. We need to have a deep understanding of the memory CPU and face the various pitfalls brought about by the continuous CPU upgrade.

I think that only Intel's tbb and Microsoft's PPL are truly trustworthy C ++ concurrency libraries.

Https://software.intel.com/en-us/node/506042 Intel? Threading Building Blocks

The http://msdn.microsoft.com/en-us/library/dd492418.aspx Parallel Patterns Library (PPL)

In addition, FaceBook also opened up a C ++ class library, which also has a concurrent data structure.

Https://github.com/facebook/folly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.