Lock principle Java, lock optimization, CAS, AQS Detailed!

  • 1, Why lock?

  • 2, the basic principles to achieve lock

    • 2.1、volatile

    • 2.2、synchronized

    • 2.3 CASE

  • 3, Java realization of a lock

    • 3.1, queue synchronizer (the AQS)

  • 4, the lock use cases

    • 4.1, ConcurrentHashMap of the principle and use


1, Why lock?

Lock - in order to solve the dirty read concurrency caused by inconsistent data problems.

2, the basic principles to achieve lock

2.1、volatile

Java programming language allows threads to access shared variables, in order to ensure shared variables can be accurately and consistently updated thread should ensure exclusive lock to get through this variable alone. Java language provides volatile, and in some cases to be more convenient than lock.

volatile to ensure the "visibility" of shared variables in a multiprocessor development. Visibility means that when a thread modifies a shared variable, another thread can read the value of this modification.

Conclusion: If the volatile variable modifier properly, and it is lower than the cost of execution of synchronized, because it does not cause the thread context switching and scheduling.

2.2、synchronized

synchronized synchronized via the lock mechanism.

First look at the use of synchronized basis to achieve synchronization: Java each object can be used as a lock.

Specific performance in the following three forms.

  • For normal synchronization method, the lock is the current instance of the object.

  • For static synchronized method, the lock is Class object of the current class.

  • A method for synchronizing blocks, the object lock is configured Synchonized brackets.

When a thread attempts to access synchronized block, it must first get the lock, the lock must be released when you exit or throw an exception.

2.2.1 synchronized implementation principle

synchronized synchronization is achieved based Monitor.

Monitor two ways to support the synchronization between threads:

  • Exclusive execution

  • cooperation

1, Java objects using the lock (lock objects obtained using synchronized) to ensure worker threads on a shared data set mutually exclusive execution.

2, using the notify / notifyAll / wait method to work between the different threads.

3, Class and Object is associated with a Monitor.

Monitor the working mechanism

  • Thread enters a synchronized method.

  • In order to continue to perform critical section, a thread must acquire the lock Monitor. If you acquire a lock is successful, it will become the owner of the watcher object. Within any one time, the supervisor objects belong to only one active thread (The Owner)

  • Who has monitored object thread can call wait () wait to enter the set (Wait Set), while monitoring the release of the lock, enter the wait state.

  • Other thread calls notify () / notifyAll () interface to set the wake-up waiting threads, these threads need to wait for the monitor to reacquire lock code following can execute wait ().

  • Synchronization method is finished, the thread exits the critical region, and release the monitor lock.

Reference document: https: //www.ibm.com/developerworks/cn/java/j-lo-synchronized

2.2.2 synchronized specific implementation

1, the synchronization code blocks using monitorenter, monitorexit instruction explicitly implemented.

2, the implicit synchronization method implemented ACC_SYNCHRONIZED marker used.

By way of example look at the specific implementation:

public class SynchronizedTest {

    public synchronized void method1(){
        System.out.println("Hello World!");
    }

    public  void method2(){
        synchronized (this){
            System.out.println("Hello World!");
        }
    }
}

After javap compiled byte code as follows:

monitorenter

Each object has a monitor, a monitor can only be a thread owns. When a thread attempts to execute the monitorenter instruction obtain the corresponding object monitor, access rules are as follows:

  • If the number entering the monitor is 0, then the thread can enter the monitor, and the monitor is set to enter the number 1, shall monitor the thread owner.

  • If the current thread already owns the monitor, only to re-enter, then enter the number into the monitor plus 1, so to achieve the synchronized keyword lock is reentrant lock.

  • If the monitor has been owned by other threads, the current thread into the blocked state, until the number into the monitor to 0, and then again try to obtain monitor.

monitorexit

Only those with the appropriate object monitor thread can execute monitorexit instruction. Each time the instruction enters monitor minus one, when released into the number of the current monitor thread is 0:00, then the blocked thread will attempt to acquire the monitor.

2.2.3 lock storage location

Lock mark in the Mark Word Java objects stored in the head.

64 JVM Mark Word Structure

2.2.3 synchronized lock optimization

JavaSE1.6 order to obtain and release locks reduce performance brought consumption, the introduction of the "biased locking" and "lightweight lock."

In JavaSE1.6, lock a total of four states, the level from low to high are: lock-free status, tend to lock status, lock status lightweight and heavyweight lock state, these states would gradually as competition upgrade.

Lock can upgrade but can not downgrade means that bias can not be downgraded to a biased locking the lock upgrade to a lightweight lock. This lock upgrade but can not downgrade strategy is designed to improve efficiency and get the lock to release the lock.

Biased locking:

The absence of lock contention in order to reduce lock contention resource overhead, the introduction of bias lock.

Lightweight lock:

Lightweight locks adaptation scenario, when the thread is alternately performed sync block.

Lock coarsening (Lock Coarsening): i.e. reduce unnecessary tightly linked to unlock, lock operation, a plurality of consecutive locks extended into a larger range locks.

Lock elimination (Lock Elimination): lock slashing is a virtual machine time compiler at run time, for some of the code requires synchronization, but can not be detected shared data latched competition will be deleted.

Adaptive spin (Adaptive Spinning): adaptive means of spin time is no longer fixed, but a spin in the state the owner of the time and lock with a lock is determined by the former. If a lock on the same object spin-wait just successfully won locks, and thread holding the lock is running, the virtual machine will think this is also very likely to be successful spin again, and then it will allow spin wait for a relatively longer period of time, such as 100 cycles. On the other hand, if the lock for a spin rarely been successful, and that in the future to acquire the lock will be possible to omit the spin process, to avoid waste of processor resources.

2.2.4 Comparison of the advantages and disadvantages lock

2.3 CASE

CAS, the Java application refers generally to concurrent or CompareAndSwap CompareAndSet, i.e. compare and swap.

1, CAS is an atomic operation, it compares the value of a memory location and modify the memory location of the new value is only equal value, to ensure that the new value is always based on the latest information calculated, if there are other threads in this this value is modified during the CAS fails. CAS returns success or the original value for determining whether the memory location CAS successful.

2, JVM CAS operation is the use of the CMPXCHG instructions provided by the processor implementation.

advantage:

  • Little competition when small system overhead.

Disadvantages:

  • Long cycle time spending big.

  • ABA problem.

  • Atomic operation can only guarantee a shared variable.

3, Java realization of a lock

3.1, queue synchronizer (the AQS)

AbstractQueuedSynchronizer queue synchronizer (hereinafter referred to as synchronizer), is used to build the base frame locks or other synchronization components.

3.1.1, it uses an int member variable indicates synchronization status.

3.1.2, built-in two-way FIFO queue to retrieve a lock queue thread work.

  • The synchronizer comprises two types of application nodes, a first node point, a node pointing to the tail, the thread lock is not acquired node creates thread safe (compareAndSetTail) was added end of the queue. Synchronous queue follow FIFO, the first node is to obtain a successful synchronization status node.

  • Did not get to lock threads will create a node, set to the end node. As shown below:

  • Thread the first node when the lock is released, it will wake up the subsequent node. The successor node will be successful in acquiring a lock set itself a head node. As shown below:

3.1.3, exclusive / shared lock acquisition

Exclusive: There is one and only one thread can acquire the lock, such as: ReentrantLock.

Shared: a plurality of threads can be simultaneously acquired lock, such as: a CountDownLatch

Exclusive formula

  • Each node spin observe their own previous node is not the Header node, if it is, go try to get a lock.

  • Exclusive lock acquisition process:

Shared:

  • Shared and exclusive difference:

  • Share lock acquisition process:

4, the lock use cases

4.1, ConcurrentHashMap of the principle and use

FIG ConcurrentHashMap class ConcurrentHashMap data structure

Conclusion: segmentation technique used by ConcurrentHashMap lock. First, the data is divided into a section of the store, and then give every piece of data with a lock, a thread holding the lock when accessing data in which a segment of time, other segments of the data can also be accessed by other threads.

Guess you like

Origin www.cnblogs.com/cxhfuujust/p/11767204.html