Java Lock Optimization Idea and JVM implementation

Source: Internet
Author: User

1. The idea and method of lock optimization

The lock optimization mentioned here refers to how the performance does not get too bad in the case of blocking. But how to optimize, in general, performance is more than the lock-free situation is almost.
It is important to note that the Trylock in Reentrantlock is biased towards a lock-free way, because in trylock judgment, it does not hang itself.
Lock optimization ideas and methods summarized, there are several.

    • Reduced lock holding time
    • Reduce lock granularity
    • Lock separation
    • Lock coarsening
    • Lock Elimination # # 1.1 reduces lock holding time
public synchronized void syncMethod(){    othercode1();    mutextMethod();    othercode2();}

Like the code above, you get a lock before you enter the method, and the other threads wait outside.
One of the optimizations here is to reduce the time that other threads wait, so lock only on programs that are thread-safe.

public void syncMethod(){    othercode1();    synchronized(this)    {        mutextMethod();    }    othercode2();}
1.2 Reduction of lock granularity

Large objects (which may be accessed by many threads) are split into small objects, greatly increasing the degree of parallelism and reducing lock contention. Reduces the lock competition, the bias lock, the lightweight lock success rate will improve.
The most typical case of reducing lock granularity is concurrenthashmap (and, of course, before 1.8).

1.3 Lock separation

The most common lock separation is read-write lock Readwritelock, according to the function to separate into read lock and write lock, so that read-read is not mutually exclusive, read-write mutex, write mutually exclusive, that is, to ensure the thread safety, but also improve the performance.
Reading and writing separation thought can extend, as long as the operation does not affect each other, the lock can be separated.
such as Linkedblockingqueue:

Remove the data from the head and release it from the tail.

1.4 Lock Coarsening

In general, in order to ensure effective concurrency between multiple threads, each thread is required to hold the lock for as short a time as possible, that is, the lock should be released immediately after using the public resources. This is the only way to wait for other threads in the lock to get resources to perform the task as early as possible. However, all things have a degree, if the same lock on the continuous request, synchronization and release, it will also consume the system's valuable resources, but it is not conducive to performance optimization.
As an example:

public void demoMethod(){    synchronized(lock){        //do sth.      }    //做其他不需要的同步的工作,但能很快执行完毕      synchronized(lock){        //do sth.      }}

This situation, according to the idea of lock coarsening, should be merged:

public void demoMethod(){    //整合成一次锁请求    synchronized(lock){        //do sth.           //做其他不需要的同步的工作,但能很快执行完毕      }}

Of course, this is a prerequisite, the premise is that those who do not need synchronization in the middle of the work is done quickly.
To cite an extreme example:

for(int i=0;i<CIRCLE;i++){    synchronized(lock){    }}

It is different to get a lock within a loop. Although the JDK will do some optimizations for this code, it might as well be written directly:

synchronized(lock){    for(int i=0;i<CIRCLE;i++){    }}

Of course, if there is a need to say that such a cycle too long, you need to give other threads do not wait too long, it can only be written in the above. If there is no such a requirement, it is better to write it directly below.

1.5 Lock Removal

Lock elimination is something at the compiler level.
In an instant compiler, if you find objects that cannot be shared, you can eliminate the lock operations of those objects.
Perhaps you may find it strange that since some objects cannot be accessed by multiple threads, why should they be locked? It is better to write code without locking it directly.

But sometimes, these locks are not written by the programmer, there are locks in the JDK implementations, such as vectors and StringBuffer, and many of the methods are locked. When we use the methods of these classes in some cases where it is not safe to thread, the compiler will eliminate lock elimination to improve performance when certain conditions are met.

Like what:

public static void main(String args[]) throws InterruptedException {    long start = System.currentTimeMillis();    for (int i = 0; i < 2000000; i++) {        createStringBuffer("JVM", "Diagnosis");    }    long bufferCost = System.currentTimeMillis() - start;    System.out.println("craeteStringBuffer: " + bufferCost + " ms");}public static String createStringBuffer(String s1, String s2) {    StringBuffer sb = new StringBuffer();    sb.append(s1);    sb.append(s2);    return sb.toString();}

The stringbuffer.append in the code above is a synchronous operation, but StringBuffer is a local variable, and the method does not return the StringBuffer, so it is not possible to have multiple threads to access it.
Then the synchronous operation in StringBuffer is meaningless at this point.

Open lock elimination is set on the JVM parameters and of course needs to be in server mode:

-server -XX:+DoEscapeAnalysis -XX:+EliminateLocks

And to open the escape analysis. the function of escape analysis is to see if variables are likely to escape the scope of the scope.
For example, the above-mentioned StringBuffer, the return of Craetestringbuffer in the above code is a string, so this local variable stringbuffer will not be used anywhere else. If you change the Craetestringbuffer to:

public static StringBuffer craeteStringBuffer(String s1, String s2) {    StringBuffer sb = new StringBuffer();    sb.append(s1);    sb.append(s2);    return sb;}

Then this stringbuffer is returned, it is possible to be used by any other place (for example, the main function will return the result put into the map Ah, etc.). Then the JVM escape analysis can be analyzed, this local variable StringBuffer escaped its scope.
So, based on the escape analysis, the JVM can determine that if the local variable StringBuffer does not escape its scope, then it can be determined that the stringbuffer is not accessed by multithreading, then you can remove these extra locks to improve performance.

2. Lock optimization within a virtual machine

The object header is introduced first, and in the JVM, each object has an object header. Mark Word, tag for object header, 32-bit (32-bit system). Describes the object's hash, lock information, garbage collection token, age. A pointer to the lock record is saved, a pointer to the monitor, a preference for the lock thread ID, and so on. Simply put, the object header is to save some systematic information.

2.1 Bias Lock

The so-called bias, is the eccentricity, that is, the lock will be biased towards the current lock thread.
Most of the time there is no competition (in most cases a synchronization block will not have multi-threaded simultaneous competition locks), so you can improve performance by bias. That is, in the absence of competition, the thread that acquired the lock once again obtains the lock, will determine whether to bias the lock to point to me, then the thread will not have to obtain the lock again, can directly enter the synchronization block.
The implementation of a bias lock is to set the tag of the object head mark to biased and write the thread ID to the object header mark.
When other threads request the same lock, the bias mode ends.
JVM default enable biased lock-xx:+usebiasedlocking
In highly competitive situations, biased locking increases the burden on the system (each time a bias is added)
Example of favor Lock:

public static List<Integer> numberList = new Vector<Integer>();public static void main(String[] args) throws InterruptedException {    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);}

Vector is a thread-safe class that uses a lock mechanism internally. Each add locks the request. The code above has only one thread of main and then repeatedly add request lock.
Use the following JVM parameters to set the bias lock:

-XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0

Biasedlockingstartupdelay indicates that a biased lock is enabled after a few seconds of system boot. The default is 4 seconds, because when the system starts, the general data race is more intense, and enabling biased locking can degrade performance.
Turn off the bias lock below:

-XX:-UseBiasedLocking
2.2 Lightweight lock

The multithreading security of Java is implemented based on the lock mechanism, and the performance of lock is often unsatisfactory.
The reason is that Monitorenter and Monitorexit, the two bytecode primitives that control multithreading synchronization, are implemented by the JVM relying on operating system mutexes (mutexes).
A mutex is a resource-intensive operation that causes a thread to hang and, in a short time, needs to be re-dispatched back to the original thread.
In order to optimize the lock mechanism of Java, the concept of lightweight locking was introduced from JAVA6.
The lightweight lock (lightweight Locking) is intended to reduce the chance of multiple threads entering the mutex, and not to replace the mutex.
It uses the CPU primitive Compare-and-swap (CAS, assembly instruction Cmpxchg) to try to remediate before entering the mutex.
If the bias lock fails, the system will perform a lightweight lock operation. Its purpose is to minimize the need to use the mutex at the operating system level, because that performance will be poor. Because the JVM itself is an application, it is desirable to resolve thread synchronization issues at the application level. To summarize, the lightweight lock is a fast locking method that, before entering the mutex, uses CAS operations to try to lock and try not to use the mutex at the operating system level to improve performance.
If the lightweight lock fails, it means there is a competition, and upgrading to a heavyweight lock (regular lock) is the synchronization method at the operating system level. In the absence of lock contention, lightweight locks reduce the performance loss that traditional locks incur by using OS mutexes. When competition is intense (lightweight locks always fail), lightweight locks do a lot of extra work, resulting in degraded performance.

2.3 Spin Lock

When the competition exists, because the lightweight lock attempt fails, it is possible to escalate directly into a heavyweight lock to use the mutex at the operating system level. It is also possible to try a spin lock again.
If a thread can get a lock quickly, it can not suspend the thread at the OS layer, let the thread do a few empty operations (spin), and keep trying to get the lock (similar to Trylock), of course, the number of cycles is limited, when the number of cycles reached, still upgraded to a heavyweight lock. So when each thread has little hold of the lock, the spin lock tries to avoid the thread being suspended at the OS level.
JDK1.6 in-xx:+usespinning Open
JDK1.7, remove this parameter and change the built-in implementation
If the synchronization block is long, spin failures can degrade system performance. If the synchronization block is short, spin is successful, saving thread suspend switching time and improving system performance.

2.4 Bias Lock, lightweight lock, Spin lock summary

The above lock is not a Java language-level lock optimization method and is built into the JVM.
First the lock is biased to avoid the performance of a thread repeatedly acquiring/releasing the same lock, if it is still the same thread to obtain the lock, try to bias the lock will be directly into the synchronization block, do not need to obtain a lock again.

Both lightweight and spin locks are designed to avoid direct invocation of mutex operations at the operating system level, because suspending a thread is a resource-intensive operation.

To avoid the use of a heavyweight lock (an operating system-level mutex), the lightweight lock is tried first, and the lightweight lock tries to obtain the lock using a CAS operation, which means there is a competition if the lightweight lock fails. But it may soon be possible to get a lock, try a spin lock, make a few empty loops of the thread, and keep trying to get the lock every time you loop. If the spin lock also fails, it can only be upgraded to a heavyweight lock.

Visible bias Lock, lightweight lock, spin lock are optimistic lock.

3. A case of error using a lock
public class IntegerLock {    static Integer i = 0;    public static class AddThread extends Thread {        public void run() {            for (int k = 0; k < 100000; k++) {                synchronized (i) {                    i++;                }            }        }    }    public static void main(String[] args) throws InterruptedException {        AddThread t1 = new AddThread();        AddThread t2 = new AddThread();        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println(i);    }}

A very elementary mistake is that the Interger is final, and after each + +, a new Interger is created and assigned to I, so the two threads compete for a different lock. So it's not thread-safe.

4. Threadlocal and its source code analysis

It may be a bit inappropriate to mention threadlocal here, but Threadlocal is a way to replace the lock. So it is necessary to mention it.

The basic idea is that you need to lock data conflicting data in a multithreaded way, and use threadlocal to provide an object instance for each thread. Different threads only access their own objects without accessing other objects. There is no need for a lock to exist.

Because SimpleDateFormat is not thread-safe, it is wrong to use it directly in multithreading. The simplest way to do this is to define a class to use synchronized packaging (similar to Collections.synchronizedmap). This can be problematic in high concurrency, where contention for synchronized results in only one thread per session, with low concurrency.
using threadlocal to encapsulate SimpleDateFormat here solves this problem:

public class Test {    static ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();    public static class ParseDate implements Runnable {        int i = 0;        public ParseDate(int i) {            this.i = i;        }        public void run() {            try {                if (tl.get() == null) {                    tl.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));                }                Date t = tl.get().parse("2016-02-16 17:00:" + i % 60);                System.out.println(i + ":" + t);            } catch (ParseException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) {        ExecutorService es = Executors.newFixedThreadPool(10);        for (int i = 0; i < 1000; i++) {            es.execute(new ParseDate(i));        }    }}

Each thread at run time determines whether the current thread has a SimpleDateFormat object:

if (tl.get() == null)

If not, a new SimpleDateFormat is bound to the current thread:

tl.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

Then use the SimpleDateFormat of the current thread to parse:

tl.get().parse("2016-02-16 17:00:" + i % 60);

In the beginning of the code, there was only one simpledateformat, using the ThreadLocal, and a simpledateformat for each of the threads.
It is important to note that it is not necessary to set a public simpledateformat to every threadlocal. need to give each one a new simpledateformat.
In hibernate, there are typical applications for threadlocal.
Let's take a look at the source code implementation of Threadlocal
First, there is a member variable in the thread class:

ThreadLocal.ThreadLocalMap threadLocals = null;

And this map is the key to Threadlocal's implementation:

public void set(T value) {    Thread t = Thread.currentThread();    ThreadLocalMap map = getMap(t);    if (map != null)        map.set(this, value);    else        createMap(t, value);}

The value corresponding to the set and get can be based on the threadlocal.
THREADLOCALMAP implementations here are similar to HashMap, but there are differences in the processing of hash collisions.
When a hash conflict occurs in Threadlocalmap, instead of resolving the conflict with a linked list like HashMap, the index + + is placed at the next index to resolve the conflict.

Java Lock Optimization Idea and JVM implementation

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.