In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "the optimization method of lock in java". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the optimization method of lock in java".
1) Lock elimination
Concept: when JVM compiles JIT (just-in-time), it scans the running context and removes locks that are unlikely to compete for shared resources, thus saving time for threads to request these locks. For example: StringBuffer's append method is a synchronous method, if the variable of type StringBuffer is a local variable, then the variable will not be used by other threads, that is, the operation of the local variable will not cause thread unsafe problems. In this scenario, JVM automatically removes the lock on the append method when JIT is compiled.
2) Lock coarsening
Concept: connect multiple consecutive locking and unlocking operations together to expand into a larger range of locks, that is, the granularity of locking is magnified. For example: lock / unlock operations in for loops generally need to be placed outside the for loop.
3) use bias locks and lightweight locks
Description: 1) in order to reduce the performance consumption caused by acquiring and releasing locks, java6 introduces biased locks and lightweight locks. 2) there are four kinds of locks, and the levels from low to high are as follows: unlocked state, biased lock, lightweight lock and heavy lock. 3) the status of the lock will gradually escalate with the competition, and can only be upgraded but not degraded. [biased Lock] 1) background: in most cases, locks are not only not multithreaded, but are always acquired by the same thread multiple times. Biased locks are introduced to make it cheaper for threads to acquire locks. 2) concept: the core idea is that the lock will be biased towards the first thread to acquire it, and if no other thread acquires the lock in the following execution, the thread holding the biased lock will never need to be synchronized. 3) purpose: a bias lock is actually an optimized lock, which aims to reduce the performance loss of data without competition. 4) principle: 1 > when a thread accesses the synchronization block and acquires the lock, the lock-biased thread ID is stored in the lock record in the object header and stack frame. 2 > in the future, when the thread enters and exits the synchronization block, it does not need to CAS to lock and unlock it, but simply determines whether there is a bias lock pointing to the current thread in the Mark Word of the object header. 5) acquisition of biased lock: 1 > whether the identification bit of the biased lock in the access Mark Word is 1, and if it is 1, it is determined to be the biased lock. Note: [1] if the identification bit of the biased lock is 0, which means that it is in an unlocked state at this time, the current thread attempts to acquire the biased lock through the CAS operation. If the lock is acquired successfully, the biased thread ID in Mark Word is set to the current thread ID; and the biased identification bit is set to 1. [2] if the identification bit of the lock bias is neither 1 nor 0 (at this time, the identification bit of the lock bias has no value), the competition occurs and the lock bias has expanded to a lightweight lock. In this case, use CAS operation to attempt to acquire the lock. 2 > if it is biased lock, determine whether the biased thread ID in Mark Word points to the current thread. If the biased thread ID points to the current thread, it indicates that the current thread has acquired the lock. 3 > if the biased thread ID does not point to the current thread, an attempt is made to acquire the biased lock through the CAS operation. If the lock is acquired successfully, the biased thread ID in Mark Word is set to the current thread ID; 4 > if CAS fails to acquire the biased lock, it indicates competition. When the global safe point is reached (there is no executing bytecode at this point in time), the thread that acquires the biased lock is suspended, the biased lock is upgraded to a lightweight lock, and then the thread blocked at the safe point continues to execute synchronization code. 6) release of the biased lock: 1 > when other threads try to acquire the biased lock, the thread holding the biased lock releases the biased lock. 2 > releasing the bias lock requires waiting for the global security point (there is no bytecode being executed at this point in time). 3 > process: first pause the thread with the biased lock, and then check whether the thread holding the biased lock is alive. If the thread is not active, the object header is set to an unlocked state. If the thread is still alive, it indicates that there is a competition at this time. The biased lock is upgraded to a lightweight lock. The thread that has just been paused then continues to execute the synchronization code. 7) advantages: locking and unlocking does not require additional consumption, and there is only a nanosecond gap compared with the execution of asynchronous methods. 8) disadvantage: if there is lock competition between threads, lock revocation will cause additional consumption. 9) description: 1) the preferred lock is activated by default a few seconds after the application starts. 2) delay can be turned off by setting-XX:BiasedLockingStartupDelay=0. 3) the bias lock can be turned off by setting-XX:-UseBiasedLocking=false, and the program will enter the lightweight lock state by default. (if the locks in the application are mostly competitive, you should turn off the biased locks.) [lightweight locks] 1) principle: 1 > when using lightweight locks (lock identification bit is 00), before the thread executes the synchronization block, JVM will first create a space in the stack frame of the current thread to store lock records And copy the Mark Word in the object header to the lock record (note: the identification field in the lock record is called Displaced Mark Word). 2 > after copying the MarkWord in the object header to the lock record in the stack frame, the virtual machine will try to use CAS to replace the MarkWord in the object header with a pointer to the lock record in the thread virtual machine stack. If no thread occupies the lock or there is no thread competing for the lock, the current thread successfully acquires the lock and executes the code in the synchronization block. 3 > if, while the thread that acquired the lock is executing the synchronization code, another thread has also completed the creation of the lock record in the stack frame and copied the MarkWord in the object header to its own lock record, and then try to use CAS to modify the MarkWord in the object header to a pointer to its own lock record However, because the thread that acquired the lock has modified the MarkWord in the object header (and is still executing the code in the synchronization body, that is, it still holds the lock), the MarkWord in the object header is different from the value of MarkWord in the current thread lock record, resulting in the failure of the CAS operation, and then the thread will constantly cycle through the CAS operation to try to replace the MarkWord in the object header with the value of MarkWord in its own lock record. If the CAS operation is successful before the end of the loop, then the thread can successfully acquire the lock. If the lock is still not acquired after the end of the loop, the lock acquisition fails, the MarkWord in the object header will be modified to a pointer to the weight lock, and the thread that failed to acquire the lock will be suspended and blocked. 4 > when the thread holding the lock restores the MarkWord in the object header to its original state using the CAS operation (replacing the pointer to the lock record in the object header with Displaced MarkWord), it is found that the MarkWord has been modified to a pointer to the heavy lock, so the CAS operation fails, and the thread releases the lock and awakens the waiting thread to start a new round of lock grabbing. Lightweight locks have expanded to heavyweight locks, and all failed threads block rather than spin. Spin lock: 1) the so-called spin lock means that the process that does not acquire the lock is allowed to run a self-loop for a period of time (turned on by default) without suspending the thread. 2) the cost of spin is that the thread will always occupy the processor if the lock takes a short time, the effect of spin waiting is very good, on the contrary, the spin lock will consume a lot of processor resources. 3) therefore, the spin wait time must be limited, beyond which the thread will be suspended before the lock has been acquired. Advantages: reduce the performance loss caused by traditional heavyweight locks without multithreading competition. Cons: if a competing thread never gets a lock, the spin will consume cpu. Application: the pursuit of response time, synchronous block execution speed is very fast. [weight lock] description: 1) the synchronized before java6 is a heavy lock, which is inefficient, because monitor relies on the Mutex Lock (mutex) of the operating system. 2) when multi-thread competes for lock, it will cause the context switch of the thread (that is, the context switch will be done when the time slice allocated by cpu has not been used up). 3) the operating system needs to switch the context of the thread from the user state to the kernel state, which takes a relatively long time and the time cost is relatively high. 4) in the mutually exclusive state, the thread that did not get the lock will be suspended and blocked, and the operation of suspending thread and resuming thread needs to be completed from user mode to kernel mode. Pros: thread contention does not use spin and does not consume cpu. Disadvantages: thread blocking and slow response time. Application: the pursuit of throughput, synchronous block execution speed is long thank you for reading, the above is the content of "lock optimization method in java", after the study of this article, I believe you have a deeper understanding of the lock optimization method in java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.