Programmers: Java I finally know these "locked" things

Author: Thousand Jue

E-mail: [email protected]

Foreword

Every interview when the interviewer will always have thrown a fatal triple high concurrency, high availability, high performance

Here Insert Picture Description
Our programmers also known as the three-high, Work today Jue Jue say this is complicated by three high school in the "lock" thing.

First of all we need to know what the java have a lock, the picture below one thousand Jue believe it can clearly illustrate the difference between java locks (picture from the network, if infringement, please contact me by mail deletion)

Here Insert Picture Description

Here one thousand Jue will take you one by one over the next java in the "lock" thing

Optimistic and pessimistic locking lock

Pessimistic locking concept: always assume the worst case, each time to take the data that others will modify the data, so be locked, others can only wait until I release the lock to get lock; lock line database, table locks read locks, write locks are this way. The synchronized and Lock java implementation class is also pessimistic locking thoughts.

Optimistic locking concept: always assume the best case, each time to take the data that others will not modify the data, so it will not lock, but when the update will be judged in the meantime has anyone been modified; generally based versions No mechanism to achieve. Java optimistic locking in CAS is the most common method.

Here Insert Picture Description

According to the above concept we can learn a simple scenario of optimistic and pessimistic locking

  1. Optimistic locking applies to the case of reading and writing less, because they do not directly read lock allows greatly improve system performance.
  2. Pessimistic locking applies to the case of write once read many fewer, because wait until after the lock is released, you can immediately get the lock to operate.

Direct that there might be a bit ignorant concept, we look at the next invocation java

//悲观锁用synchronized实现
public synchronized  void test(){//执行相应的操作}
//悲观锁用Lock实现
Lock lock = new ReentrantLock();
public void testLock(){   
    lock.lock();
    //TODO 执行相应的操作
    lock.unlock();
}
//乐观锁
AtomicInteger atomicInteger = new AtomicInteger();
public void testCAS(){
  atomicInteger.incrementAndGet();
}
复制代码

See more than we can see is called pessimistic locking are directly locked to ensure the synchronization of resources, this time many of my friends will ask why not optimistic locking lock resource synchronization can be achieved it, yes, and why, Look on 1000 Jue.

Here Insert Picture Description

Why not optimistic locking lock resource synchronization can be achieved it?

Since the beginning we say that the optimistic locking is the most important way to achieve CAS algorithm.

CAS is the Compare and Swap, then that is relatively exchange, jdk5 been added and contracting java.util.concurrent. *, That the following class implements an algorithm using a CAS different from the optimistic locking synchronouse synchronization locks.

CAS has three operands, memory value V, the expected value of the old A, to modify the new value B . If and only if the expected value of the A and V are the same memory value, the memory value V revised to B, or do nothing.

CAS is this allows us to achieve "lock" lock-free way, CAS, although very strong, but there are several problems

  1. ABA problem . Because the CAS needs to check the value at the time of operation under values are not changed, if not changed is updated, but if a value is A, became a B, he is a A, you will find that when using CAS inspection its value has not changed, but actually changed. Solutions ABA problem is to use a version number. The version number is added in front of variables, each variable is updated when the version number plus one, then it will become ABA 1A-2B-3A.

    From the beginning of the JDK atomic Java1.5 package provides a class AtomicStampedReference to address the ABA problem. The method of action of this class is compareAndSet checks the current reference is equal to the expected reference and the current mark is equal to the expected flag, if all equal Atomically the reference value and the flag is set to the given updated value.

    About ABA reference documentation problem: blog.hesey.net/2011/09/res...

  2. Long cycle time spending big . If the time is not successful spin CAS, it will bring a very large CPU execution cost.

  3. Atomic operation can only guarantee a shared variable . When performing operations on a shared variable, we can use the CAS cycle approach to ensure an atomic operation, but when multiple shared variables operating cycle CAS can not guarantee atomic operations, this time you can use the lock, or a tricky way, is to merge multiple shared variables into a shared variable to operate. For example there are two shared variables i = 2, j = a, merge at ij = 2a, and to operate with CAS ij.

From the beginning Java1.5 JDK classes AtomicReference provided to ensure the reference atom between objects, you can put an object in the plurality of variables on the CAS operation is performed.

Spin locks and adaptability spin locks

Spin lock: To avoid thread synchronization acquiring resources, suspend and resume the thread frequently, allowing the original thread has to wait for the cycle to acquire the lock, which is a spin lock.

Adaptive spinlock: adaptive adaptive spin lock time is not reflected in the spin fixed. If a lock on the same object before spin thread lock just won, and now holds the lock threads are running, the VM will think that this spin is also likely to be successful, thereby allowing the thread waits for a relatively longer, such as 100 cycles. Conversely, if a little lock spins won is successful, then after acquiring the lock when the spin-off process may be omitted to avoid a waste of processor resources.

The above concepts from the network.

Here Insert Picture Description

Shortcoming spin lock: While waiting for the spin to avoid the overhead of thread switching, but it takes up processor time. If the lock is occupied for a short time, waiting for the spin effect will be very good. On the other hand, if the lock is occupied for a long time, it will spin thread white waste processor resources. So, spin the waiting time must have a certain limit, if the spin exceeds the limited number of times (the default is 10, you can use -XX: PreBlockSpin to change) without success to obtain a lock, it should be hung thread. JDK6 enabled by default spin locks.

Principle spin lock implementation is also CAS, said above principle optimistic locking is achieved CAS can achieve lock-free way to lock, it is to spin the spin lock add an infinite loop until value changes his success.

There are three common spin lock lock form: TicketLock, CLHlock and MCSlock (if you want to know friends message to me, I alone single opening chapter).

No lock and biased locking lock and lightweight and heavyweight lock

The four locks are actually four states lock, this time I believe certainly have a reader asked what the status of the lock, the lock is where it exists.

Here Insert Picture Description

Do not worry, to go along with one thousand Jue, offer to get hand cramps.

Where is there lock it?

Java objects latched head of Mark Word. Mark Word to store not only the default lock flag, also holds the object hashCode and other information. Runs, according to the state of the lock, modify memory contents of Mark Work. If the object is an array type, the virtual machine 3 stores word objects wide head, if the object type is not an array, the word width stored in the object 2 with the head. In the 32-bit virtual machines, word width equal to four bytes, 32bit. First-class knowledge about the object, refer to the Java virtual machine related articles.

Mark Word there are locks on content

Memory contents Flag status
Object hashcode, objects generational age, is biased locking (0) 01 no lock
Pointers to lock records 00 Lightweight lock
Heavyweight locks pointer pointing 10 Heavyweight lock
Bias thread ID, timestamp bias, the object generational age, is biased locking (1) 01 Biased locking

No lock: is not locked, no resources locked, so that all threads can access a resource, but at the same time only one resource can be modified successfully.

Biased locking: A thread race condition does not exist in most cases, will consume synchronization performance, while biased locking is optimized for the lock, synchronization can be eliminated to improve performance. When a thread acquires the lock, the lock flag will object header set to be 01 to enter bias mode. Biased locking can make a thread has been holding the lock, the lock needs to compete in other threads of time, and then release the lock.

Lightweight lock: After obtaining biased locking thread 1, thread 2 into the state competition, you need to get the thread 1 locks held, it will be upgraded to lightweight biased locking lock, other threads will try to get through in the form of spin lock.

Heavyweight lock: When a spin over a certain number of times or a thread holding the lock, a thread in the spin, another third visit, lightweight heavyweight lock lock escalation, then wait for the lock thread They will enter the blocked state.

Overall lock status upgrade process: biased locking ----> Lightweight lock ----> heavyweight lock

Fair and unfair lock lock

Fair locks: that each thread can get a lock.

Unfair lock: You can not guarantee that each thread can get a lock.

There is a language description to see if a bit ignorant, for example.

Lock is fair when you go to the cafeteria line up Dafan Dafan if honestly, then that is fair locks.

When the lock is unfair to the cafeteria Dafan you can not line up in front of a person who lay meal, you can directly Dafan, do not control how many people did not Dafan. In this case the lock is unfair.

Here Insert Picture Description

java among the fair locks, locks for non-fair

//公平锁
ReentrantLock lock = new ReentrantLock(true);
//非公平锁
ReentrantLock lock = new ReentrantLock(false);
复制代码

Not discussed the specific principles, if you want to know why this realization, you can leave a message to me.

Applicable scenario is: the thread holding time is longer than the thread switching time is still a fair lock, on the contrary a number of non-equity locked.

Reentrant and non-reentrant lock lock

Is reentrant lock lock can be called repeatedly, after a lock out method, can still locked inside, and the deadlock (provided that the same object or class) does not occur, so that the lock is called reentrant lock. ReentrantLock are synchronized and reentrant lock.

You have looked at the concept may be a bit ignorant, but to see it realized that this stuff is very simple.

public class Test implements Runnable{
    public static void main(String []args){
        Test test = new Test();
        for(int i = 0; i < 5; i++){
            new Thread(test).start();
        }
    }
    @Override
    public void run() {
        out();
    }

    public synchronized void out(){
        System.out.println(Thread.currentThread().getName());
        in();
    }

    public synchronized void in(){
        System.out.println(Thread.currentThread().getName());
    }
}
复制代码

// output results are as follows, we can see no threads are blocked

Thread-2 Thread-2 Thread-4 Thread-4 Thread-3 Thread-3 Thread-1 Thread-1 Thread-0 Thread-0

Non-reentrant lock is a lock can not be called repeatedly after lock out method, which can not be used in the lock, and this time the lock will be blocked until the lock is released you will get out of the inside of the lock. This will produce a deadlock situation.

Non-reentrant lock to achieve the following:

public class NoLock {
    private boolean isLocked = false;
    public synchronized  void lock() throws InterruptedException {
        while (isLocked){
            wait();
        }
        isLocked = true;
    }
    public synchronized void unlock(){
        isLocked = false;
        notify();
    }
}
复制代码

Exclusive locks and shared locks

Exclusive lock: The lock can only be held once every one thread, synchronized and are exclusive lock ReentrantLock

Shared locks: The locks can be multiple threads total. Thread acquires a shared lock can only read data, the data can not be modified.

ReentrantReadWriteLock There are two locks: ReadLock and WriteLock, known by the Italian word, a read lock a write lock, collectively, the "read-write lock." Read lock is a shared lock, write lock is an exclusive lock

to sum up

java "lock" this thing is over, there are many aspects of the principle of things, thousands Jue no in-depth introduction, on the one hand because it is my level is not enough, on the one hand because of space problems, if the reader read this article What areas of doubt can leave a message to tell me.

Finally, I beg you to read this article written by feel okay, trouble trouble you a little hand points attention to it, point a praise it, your praise and attention is the driving force of one thousand Jue writing.

The end of 2019, 2020 hope to better it, I wish you all a happy New Year.

Guess you like

Origin juejin.im/post/5e0b1b025188253aa57a645a