The common lock mechanism in Java thread concurrency details _java

Source: Internet
Author: User

With the development of Internet, more and more Internet enterprises are confronted with the problem of concurrent security caused by the expansion of user volume. This paper mainly introduces several kinds of lock mechanisms which are common in Java concurrency.

1. Bias Lock

The bias lock is a kind of locking optimization mechanism proposed by JDK1.6. The core idea is that if the program is not competing, then cancel the thread synchronization operation that has already acquired the lock. In other words, if a lock is acquired by the thread, it goes into the biased mode, and when the thread requests the lock again, it does not need to do the related synchronization operation, thus saving the operation time, if there is another thread between the lock request, then the lock exit bias mode. Using-xx:+usebiasedlocking in the JVM

Package jvmproject;
Import java.util.List;
Import Java.util.Vector;
public class Biased {public
  static list<integer> numberlist = new vector<integer> ();
  public static void Main (string[] args) {
    long begin = System.currenttimemillis ();
    int count = 0;
    int startnum = 0;
    while (count<10000000) {
      numberlist.add (startnum);
      startnum+=2;
      count++;    
    }
    Long end = System.currenttimemillis ();
    System.out.println (End-begin);
  }

Initializes a vector, adds 10 million integer objects to it, and then outputs a time difference. This is used to test the performance of the bias lock. Why use vectors instead of ArrayList?

Because ArrayList are thread-insecure, vectors are thread-safe. This may not be specific enough, you can look at the source bar.

Almost all operations in vectors are sychronized, and ArrayList are not, so vectors are thread safe.

Next, we will test the effect of turning on the bias lock and not opening the bias lock on the performance of the program.

The configuration JVM startup (open bias Lock) parameter is:

The configuration JVM startup (turn off bias Lock) parameter is:

perfect! Turn on the lock of the program running time is significantly shorter, open bias lock than open bias lock, in a single thread to operate an object synchronization method, there is a certain advantage. In fact, it can be understood that when only one thread operates a vector object with a synchronization method, the operation of the vector is transformed into an operation on the ArrayList.

The bias lock in the lock competition in the situation is not too strong optimization effect, because a lot of competition will cause the lock thread to keep switching, locks are difficult to maintain in the biased mode, at this point, the use of bias locks not only can not be optimized performance, but it is possible to reduce the performance of the system, so in the fierce competition in the occasion, you can try to use

The-xx:-usebiastedlocking parameter disables the bias lock.

2. Lightweight lock

If the lock fails, the Java Virtual machine makes the thread request a lightweight lock, a lightweight lock inside the virtual machine, and a Basicobjectlock object that consists of a Basiclock object and a Java object pointer holding the lock. The Basicobjectlock object is placed in the Java stack frame. The Displaced_header field is also maintained inside the Basiclock object to back up Mark Word in the header of the object.

When a thread holds an object's lock, the object's head mark Word information is as follows

[PTR |00] Locked

The two-bit bit at the end is 00, and the entire mark Word is a pointer to the Basiclock object. Because the Basicobjectlock object is in the thread stack, the pointer necessarily points to the line stacks space holding the lock. When you need to determine whether a thread holds the object, simply determine whether the object header's pointer is in the current thread's stack address range. Also, the displaced_header of the Basiclock object backs up the mark Word content of the original object, and the obj field of the Basicobjectlock object points to the head of the object holding the lock.

3. Heavy-grade Lock

When a lightweight lock fails, the virtual machine uses a heavyweight lock. When using a heavyweight lock, the object's Mark Word is as follows:

[PTR |10] Monitor

Heavy lock during operation, the thread may be suspended by the operating system level, and if so, the cost of switching and invoking between threads can be greatly improved.

4. Spin Lock

A spin lock enables a thread to perform an empty loop without being suspended while not acquiring a lock, (that is, the so-called spin, which is the execution of the empty loop itself), and if the thread can acquire a lock after several empty loops, continue executing. If the thread is still unable to get the lock, it will be suspended.

With a spin lock, the probability of a thread being suspended is relatively reduced, and the consistency of thread execution is relatively enhanced. Therefore, the competition for those locks is not very intense, lock takes up a very short time concurrent thread, has certain positive significance, but for the lock competition is intense, the single thread lock occupies the very long time the concurrent program, the spin lock in spins waits, often resolutely cannot obtain the corresponding lock, not only wasted the CPU time, In the end it is unavoidable to be suspended operation, instead of wasting the resources of the system.

In JDK1.6, the Java Virtual machine provides-xx:+usespinning parameters to unlock the spin lock and uses the-xx:preblockspin parameter to set the number of spin locks to wait.

At the beginning of JDK1.7, the parameters of the spin lock are canceled, the virtual machine no longer supports the user-configured spin lock, the spin lock is always performed, and the number of spin locks is automatically adjusted by the virtual machine.

Related Article

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.