In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "the implementation principle of synchronized and what is the lock optimization method". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "the implementation principle of synchronized and what the lock optimization method is" can help you solve your doubts.
1. The implementation principle of synchronized and lock optimization?
The realization principle of synchronized
Synchronized acts on "methods" or "code blocks" to ensure that the decorated code can only be accessed by one thread at a time.
When synchronized modifies the code block, JVM uses two instructions "monitorenter and monitorexit" to achieve synchronization.
When synchronized modifies the synchronization method, JVM uses the "ACC_SYNCHRONIZED" tag to achieve synchronization
Monitorenter, monitorexit, or ACC_SYNCHRONIZED are all "implemented based on Monitor"
There is an object header in the instance object, and a Mark Word,Mark Word pointer points to "monitor" in the object header.
Monitor is actually a "synchronization tool" or a "synchronization mechanism".
In the Java virtual machine (HotSpot), Monitor is "implemented by ObjectMonitor". ObjectMonitor reflects the working principle of Monitor ~
ObjectMonitor () {_ header = NULL; _ count = 0; / record the number of times the thread acquired the lock _ waiters = 0, _ recursions = 0; / / the number of reentrants of the lock _ object = NULL; _ owner = NULL; / / points to the thread holding the ObjectMonitor object _ WaitSet = NULL / / threads in the wait state will be added to _ WaitSet _ WaitSetLock = 0; _ Responsible = NULL; _ succ = NULL; _ cxq = NULL; FreeNext = NULL; _ EntryList = NULL; / / threads in the block state waiting for lock will be added to the list _ SpinFreq = 0; _ SpinClock = 0; OwnerIsThread = 0;} copy code
Several key attributes of ObjectMonitor, count, recursions, owner, WaitSet, _ EntryList, reflect the working principle of monitor.
Lock optimization
Before discussing lock optimization, let's take a look at the structure diagram of Mark Word in the JAVA object header (32-bit JVM).
Mark Word stores the running data of the object itself, such as "hash code, GC generation age, lock status flag, bias timestamp (Epoch)", etc. Why does it distinguish several lock states such as "bias lock, lightweight lock, heavy lock" and so on?
❝
Before JDK1.6, the implementation of synchronized directly called ObjectMonitor's enter and exit, which was called a "heavyweight lock." Starting from JDK6, the HotSpot virtual machine development team optimizes locks in Java, such as adaptive spin, lock elimination, lock coarsening, lightweight locks, and biased locks.
❞
Biased locks: in the absence of competition, the entire synchronization is eliminated and CAS operations are not done.
Lightweight lock: when there is no multithreading competition, it reduces the performance consumption caused by the mutex of the operating system compared to the heavy lock. However, if there is lock contention, there is an additional overhead of CAS operations in addition to the mutex itself.
Spin lock: reduces unnecessary CPU context switching. Spin locking is used when a lightweight lock is upgraded to a heavyweight lock
Lock coarsening: multiple consecutive locking and unlocking operations are connected together to expand into a larger range of locks.
❝
For example, buy a ticket to enter the zoo. The teacher takes a group of children to visit. If the ticket inspector knows that they are a group, they can regard them as a whole (lock rent) and check the tickets at once, instead of looking for them one by one.
❞
Lock elimination: when the virtual machine just-in-time compiler is running, it requires synchronization on some code, but locks that are detected to be impossible to compete for shared data are eliminated.
Interested friends can take a look at my article: Synchronized Analysis-if you are willing to peel off my heart layer by layer [1]
2. ThreadLocal principle, pay attention to use, what are the application scenarios?
Answer four main points:
What is ThreadLocal?
ThreadLocal principle
Pay attention to the use of ThreadLocal
Application scenarios of ThreadLocal
What is ThreadLocal?
ThreadLocal, that is, thread local variables. If you create a ThreadLocal variable, then each thread accessing the variable will have a local copy of the variable. When multiple threads operate on this variable, they are actually operating on variables in their own local memory, thus playing the role of thread isolation and avoiding thread safety problems.
/ / create a ThreadLocal variable static ThreadLocal localVariable = new ThreadLocal (); copy the code
ThreadLocal principle
ThreadLocal memory structure diagram:
It can be seen from the structure diagram that:
The Thread object holds a member variable of ThreadLocal.ThreadLocalMap.
ThreadLocalMap maintains an array of Entry internally, where each Entry represents a complete object, key is the ThreadLocal itself, and value is the generic value of ThreadLocal.
Compared with these key source codes, it is easier to understand.
Public class Thread implements Runnable {/ / ThreadLocal.ThreadLocalMap is an attribute of Thread ThreadLocal.ThreadLocalMap threadLocals = null;} copy code
Key methods set () and get () in ThreadLocal
Public void set (T value) {Thread t = Thread.currentThread (); / / get the current thread t ThreadLocalMap map = getMap (t); / / get the ThreadLocalMap if (map! = null) map.set (this, value) according to the current thread; / / set the KPerry V to else createMap (t, value) in ThreadLocalMap / / create a new ThreadLocalMap} public T get () {Thread t = Thread.currentThread (); / / get the current thread t ThreadLocalMap map = getMap (t); / / get the ThreadLocalMap if (map! = null) {/ / get the corresponding Value from the this (that is, the ThreadLoca object), that is, the ThreadLocal generic value ThreadLocalMap.Entry e = map.getEntry (this) If (e! = null) {@ SuppressWarnings ("unchecked") T result = (T) e.value; return result;}} return setInitialValue ();} copy the code
ThreadLocalMap's Entry array
Static class ThreadLocalMap {static class Entry extends WeakReference
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.