Series directory

Today is another day of learning

Date: 2019-6-27 21:10:45

The lock

The concept of the lock

spinlocks

  • Concept: Keep trying to update the data using CAS without dropping CPU events until it succeeds
  • Example: AtomicInt uses spin locks to ensure atomicity of data
  • It’s also a kind of optimism lock

Optimistic locking

Pessimistic locking

Exclusive lock (write lock)

Shared lock (read lock)

Reentrant lock

  • Synchronized is a reentrant lock
    • The same thread, after acquiring a lock, can continue to call the code synchronized with the same lock.
public synchronized void task(Object arg){
	System.out.print(Thread.currentThread() + "Commence execution" + arg);
    if(arg == null) {this.task(new Object());   
    }
    System.out.print(Thread.currentThread() + "End of execution" + arg);
}

//main
new Obj().task(null);
Copy the code

Sync key

synchronized

Thread closed

Lock elimination

  • For some code with local variables, thread-safety issues may not arise and the lock will be eliminated
public void genStr(a){
    //JIT optimization eliminates locking
    StringBuffer sb = new StringBuffer();
    sb.append("a");
    sb.append("b");
    sb.append("c");
}
Copy the code

Lock coarsening

JIT compilation optimizations that belong to the runtime

  • The range of locks will be expanded
  • Sych is locked out of the for loop
public class LockDemo01{
    int count;
  	public void runTest(a){
     	 for(int i = 0; i < 10000; i++){
          	synchronized(this){ count++; }}}}Copy the code

View the JIT-optimized code through the JitWatch

www.cnblogs.com/stevenczp/p… www.cnblogs.com/stevenczp/p…

1, Output JIT log (Windows) placed hsDIS dynamic link library eclise, IDEA and other tools in jre/bin/server, Combined with the JVM parameter – server – XX: + UnlockDiagnosticVMOptions – XX: + PrintAssembly – XX: XX: + LogCompilation – LogFile = jit. Log

2. Tool installation and download github.com/AdoptOpenJD… Run MVN clean compile exec: Java via Maven

4, in the analysis result, select the specified class, and then select the specific method on the right, the jit compilation result will pop up

Synchronization keyword locking principle

General structure

Mark word in Obj Head

Mapping between BitFields and State.

  • LockRecord Address Store thread stack LockRecord Address ** >>> lightweight Lock **
  • Monitor Address The Address where Monitor OBJ is stored >>> Heavyweight lock
    • Because monitor OBJ is involved, it can be considered heavyweight
  • TheadId thread Id >>> bias lock in JVM

HotspotOverview.pdf

The lock status changes

No lock -> Lightweight lock

CAS! CAS! CAS! CAS! CAS! CAS! CAS!

lock

unlock

Biased locks -> Lightweight locks

  • Question: How is thread reentrant determined
    • Because the Lock Record Address records the stack Address of the thread that currently holds the Lock, it is possible to check whether reentrant is possible

Lightweight lock -> Heavyweight lock

The state of the lock in the object header

Heavyweight lock/lightweight lock/unlocked

Relevant code: SRC. Share. Vm. Runtime. ObjectMonitor

  1. When thread -1 requests to hold a lock, if the object is 01 (UNLOCK), it acquires the lock and sets the flag position in the object’s header to lightweight lock (00).
  2. The thread requests the lock through CAS spin
  3. When the object state bit is 00, another thread requests the lock, and the thread first tries to acquire the lock by means of CAS spin. When the number of attempts fails to obtain the lock, the object state changes to 10.
  4. The reason for not using spin wait here is that spin consumes a lot of resources
  5. It is heavyweight because you operate on two objects > the original object and the Monitor object
  6. In the object’s monitor, _owner will change to thread-1, and the new request thread will be placed in _EntryList to wait
  7. _EntryList is a scramble queue!!
  8. Threads can release _owner in two ways
  9. When the thread holding the lock completes execution, monitorExit is monitorExit.
  10. The wait set _waiters is entered after invoking the wait method on the object
  11. For a thread to enter the _waiters queue, the _owner thread needs to invoke wait, so wait()/notify() needs to be performed in the synchronized code block
  12. Because the wait Set is Set, notify does not know which to wake up

Biased locking

Priority: Unlocked >>> Biased locking >>> Lightweight >>> Heavyweight

  • The flag bit for the lightweight lock is stored in the MarkWord of the object header and is turned on by default
  • The specific process
    1. When thread 1 requests to hold the lock, it will check the flag bit biased towards the lock first. If the flag bit is opened as 1, it will modify the thread information through CAS.
    2. The thread information records the ThreadId of the thread that currently acquired the biased lock
    3. If it works, you have the lock
    4. If the change fails through the CAS and the thread status is 01, the upgrade to the lightweight lock is cleared flag
    5. Bias lock release will clear thread information
  • Why biased locking
    • Because the JVM is designed to assume that, in most cases, there is no lock contention, there is no need to change flag bits frequently, reducing the possibility of becoming a heavyweight lock. Improved performance.

reference

open jdk

  • Source: hg.openjdk.java.net/jdk10/jdk10… / github.com/frohoff/jdk…

Copyright statement

  • Author: Liu Xi
  • This paper links: www.yuque.com/diamond/ndv…
  • Copyright Notice: All articles on this blog are subject to a CC BY-SA 4.0 license unless otherwise stated. Reprint please indicate the source!
  • Launch date: 2019-6-27 21:10:45