When the interviewer hate you synchronized poor performance, you get the article suspended or beaten him (ReentrantLock and synchronized Past and Present)

One day, you get into a giant interview. Among the restless, a bald middle-aged man, dressed in a gray a plaid shirt, wearing a pair of thick glasses lens of 9mm, steady as a rock toward you suddenly said:. "This is you young folks to interview it."

Was surprised, this fear is not a fairy-level architect. But still pretending to be calm: "interviewer Hello, I am xxx ..."

The interview process ...... interviewer readily thrown sentence: "to speak briefly synchronized keyword it."

Simple talk about? ? ? Ah, the interviewer is a nice person.
Coupled with the careful preparation before my interview, and better educated talent, and casual cool Hui Fang Qiu, we will be able to deeply impressed him.
Then: "It's very simple,

synchronized keyword can be used in the method can also be used () including the object as a method thereof, a method to ensure that the internal thread-safe code is a mutex. "

The interviewer asked:

  • synchronized heavyweight lock right
  • it sync reentrant
  • sync it fair
  • The reason sync lock that affect performance
  • ReentrantLock heavyweight lock right
  • What is the difference with synchronized ReentrantLock know
  • Is not much travel should be replaced with a lightweight lock synchronized

What are these? ? ? ? ?
"You go back to such notice it."

<Shiver>

Following entered, if you understand the above questions, able to skillfully answer, and that the underlying principles for the java concurrency more you know, has been more thorough.
In most cases the programmer may direct the method used to add synchronized keyword to ensure safety, but the lack of understanding of its underlying, often overlooked performance.

First, talk story ReentrantLock and synchronized, you probably will be able to understand the performance difference between "lock"
1, sync Tucao

Before jdk1.6 version.

  • sync each lock will call the operating system to ensure the implementation of thread safety
  • Each code block is executed, to be involved transition "user mode" to the "kernel mode" in
  • So was the majority sync program ape Tucao, turtle speed codes

Suppose there is a method

public void function() {
    System.out.println("Hello world!");
    // 各种乱起八遭的代码
}

Assuming that it is now running smoothly on a single server, the boss feel very satisfied.
But one day, the business has changed, there are multiple threads to access it over, it becomes thread-safe.
One yard farmers will modify this code, plus a synchronized keyword, thread-safe, to prevent being fired by the boss.
But this method, sometimes there will be multi-threaded access, can most of the time only one thread, look at it from time to time to touch the bottom line.
Then due to the presence of synchronized, each run as snail.
Finally, the code farmers got fired.

So the sun's received numerous complaints java homeless, said synchronized inefficient, lead to code turtle crawl speed, himself fired.
Among the flooding of spittle, sun firm found that the situation is bad, so check it out dedicated staff sneak into the market situation.
According to gather intelligence to see, a piece of code

  • It sometimes multiple threads of execution
  • But most of the time, are single-threaded execution

So many times in fact, less than a lock, but sync or will seriously affect the performance
so the program ape who hope to have a lock, in the absence of the thread can be competitive, the more light-weight.

2, ReentrantLock turned out

Before jdk1.6, because the sync performance worrying
so there classmate could not understand, he wrote a set of technology, he called

  • Gen Lee Road (Doug Lea)

He also wrote a lot of class, a lot of class in juc packages are written by him
(juc do not know to go back up basis)
of which there are famous ReentrantLock

  • Will speed faster than sync

Lock this kind of thing, why go to the trouble of the underlying operating system do?
ReentrantLock So he developed, to replace sync keyword
but why not replace it succeed?

  • Since sync is the sun's own son

But I have to admit ReentrantLock is very good
for now, and also comparable sync

  • ReentrantLock soon as possible to solve nothing more than the level locked in java
  • Rather than take the trouble operating system

For example, the following code is unfair lock lock

final void lock() {
    if (compareAndSetState(0, 1)) // CAS将0改为1,可以一步加锁成功
        setExclusiveOwnerThread(Thread.currentThread());
    else
        acquire(1);
}

(If this code to see go Bubu basis do not understand it)
the default by the following non-realized fair locks
can be found according to the code when only one thread execution

  • The method of entering the lock, directly flag from 0 to 1 replacement, and can directly lock successful
  • In one step, does not involve any operating system kernel switching period, the level of java has been locked completed, performance than the original sync Cengceng rub do not know how many times faster

Let's look at its fair locks for part of the code
(if you are lazy, you can not look directly to see my interpretation)

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) { // 如果标志位0,说明没线程持有锁
        if (!hasQueuedPredecessors() && // 如果没有线程在排队等锁
            compareAndSetState(0, acquires)) { // CAS改标志位
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

Lock lock fair and unfair difference is more than two lock fair judgment

  • There is no judgment thread holds the (flag is 0)
  • There are no threads waiting in the queue

CAS then lock
if it is single-threaded, then direct two if, plus a lock on the success of the CAS.
same

  • In one step, does not involve any operating system kernel switching period, the level of java has been locked completed, performance than the original sync Cengceng rub do not know how many times faster

Gen Lee Road (Doug Lea) instantly been called the altar (was amazing)

sync optimization

sync Tucao, ReentrantLock touted
this time the sun's certainly sit still

  • You know, sync but the sun's own son
  • The company is single-handedly bringing up the sun
  • And now halfway decent ReentrantLock being touted, sync discarded people

the sun's certainly not go on like this thinking, so to sync a lot of optimization.
So after jdk1.7, sync performance has also been improved
sun reuse company began its own son

  • Later originally adopted in jdk1.8 ConcurrentHashMap turn into a sync key in ReentrantLock

There are so many changes in sync
(the following from "in-depth understanding of java virtual machine")

  1. Lock eliminate
    such
public String concatString(String s1,String s2,String s3){
    return s1+s2+s3; 
}
// 上面的代码会被转化为下面的代码
public String concatString(String s1,String s2,String s3){ 
	StringBuffer sb = new StringBuffer();
	sb.append(s1);
	sb.append(s2);
	sb.append(s3);
	return sb.toString();
}

StringBuffer methods is sync with the
(unknown back up classes)
in execution time, because they do not involve thread safety in this code
so automatically optimized for
unlocked!

  1. Lock foul language (see the code you will understand)
    (read back makeup)
// 其实就是上面的代码
public String concatString(String s1,String s2,String s3){ 
	StringBuffer sb = new StringBuffer();
	sb.append(s1);
	sb.append(s2);
	sb.append(s3);
	return sb.toString();
}

Each is a sync append
it will be optimized (read just fine, just for your understanding)

sync
	public String concatString(String s1,String s2,String s3){ 
		StringBuffer sb = new StringBuffer();
		sb.append(s1); // 这里的 sync 没啦
		sb.append(s2); // 这里的 sync 没啦
		sb.append(s3); // 这里的 sync 没啦
		return sb.toString();
	}
sync
  1. Biased locking

Biased locking of "bias" is eccentric "partial" favoritism "partial", it means that the lock will be biased in favor of the first to get its thread, if in the next execution, the lock has not been other threads acquisition, holds biased locking thread you will never need to re-synchronize

When there is another thread to try to acquire the lock, it came to an end bias mode

  1. Spin lock
    If the physical machine that allows two or more threads execute in parallel, we can get behind the thread "wait a minute", they will not give up the processor execution time, but try a few times while loop several locked, if locked soon after several successful, it does not relate to suspend and resume the thread, just spend a little a little bit CPU.
    Spin default number is 10.
    If a thread spin lock success, JVM will feel that the probability of the next spin lock this thread will be a great success, it will enhance the look a little spin-count
  2. Lock inflation
    if lightweight locking is not possible, it had to become a heavyweight lock.

Article here came to an end, I was a university student, oh, like learning little friends can comment exchange, or plus interest, to learn together more easily.
Quality triple!

Released three original articles · won praise 0 · Views 20

Guess you like

Origin blog.csdn.net/weixin_44051223/article/details/104572320