Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize Java Lock

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to optimize Java locks". In daily operation, I believe many people have doubts about how to optimize Java locks. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to optimize Java locks". Next, please follow the editor to study!

Lock optimization

Lock optimization here mainly refers to the optimization of synchronized by JVM.

Spin lock

Mutex synchronization is very expensive to enter the blocking state and should be avoided as much as possible. In many applications, the locked state of shared data only lasts for a short period of time. The idea of a spin lock is to let a thread execute a busy loop (spin) for a period of time when requesting a lock for shared data, and if the lock can be acquired during that time, it can avoid entering a blocking state.

Although spin lock can avoid entering blocking state and reduce overhead, it requires busy loop operation to take up CPU time, and it is only suitable for scenarios where the lock state of shared data is very short.

An adaptive spin lock is introduced in JDK 1.6. Adaptation means that the number of spins is no longer fixed, but is determined by the number of spins on the same lock and the state of the lock's owner.

Lock elimination

Lock elimination refers to the elimination of locks on shared data that are detected to be impossible to compete.

Lock elimination is mainly supported by escape analysis. If the shared data on the heap cannot escape and be accessed by other threads, they can be treated as private data and their locks can be eliminated.

For some code that does not seem to be locked, a lot of locks are implicitly added. For example, the following string concatenation code implicitly adds a lock:

Public static String concatString (String S1, String S2, String S3) {return S1 + S2 + S3;}

String is an immutable class, and the compiler will automatically optimize the splicing of String. Prior to JDK 1.5, it was converted to a continuous append () operation of the StringBuffer object:

Public static String concatString (String S1, String S2, String S3) {StringBuffer sb = new StringBuffer (); sb.append (S1); sb.append (S2); sb.append (S3); return sb.toString ();}

There is a synchronization block in each append () method. The virtual machine looks at the variable sb and soon finds that its dynamic scope is limited to the inside of the concatString () method. That is, all references to sb never escape outside the concatString () method, and other threads cannot access it, so it can be eliminated.

Lock coarsening

If a series of consecutive operations repeatedly lock and unlock the same object, frequent locking operations will lead to performance loss.

This is the case with the successive append () methods in the sample code in the previous section. If the virtual machine detects that the same object is locked by such a series of piecemeal operations, the scope of locking will be extended (coarsening) to the outside of the entire sequence of operations. The sample code for the previous section extends to before the first append () operation until after the last append () operation, so that it only needs to be locked once.

Lightweight lock

JDK 1.6introduces biased locks and lightweight locks, so that locks have four states: no lock state (unlocked), bias lock state (biasble), lightweight lock state (lightweight locked), and heavy lock state (inflated).

Heavyweight locks are usually referred to as synchronized object locks.

The following is the memory layout of the HotSpot virtual machine object header, which is called Mark Word. Tag bits corresponds to five states, which are given in the state table on the right. In addition to the marked for gc status, the other four states have been introduced earlier.

On the left side of the figure is a threaded virtual machine stack with a portion of an area called Lock Record, which is created during a lightweight lock run to hold the Mark Word of the lock object. On the right is a lock object that contains Mark Word and other information.

Lightweight locks use CAS operations to avoid the overhead of using mutexes in heavy locks compared to traditional heavy locks. For the vast majority of locks, there is no competition in the whole synchronization cycle, so it is not necessary to use mutexes for synchronization. We can first use CAS operations for synchronization, and then use mutexes for synchronization if CAS fails.

When trying to acquire a lock object, if the lock object is marked 0 01, the lock object's unlocked state is unlocked. At this point, the virtual machine creates a Lock Record in the virtual machine stack of the current thread, and then uses the CAS operation to update the Mark Word of the object to the Lock Record pointer. If the CAS operation succeeds, the thread acquires the lock on the object, and the lock flag of the object's Mark Word changes to 00, indicating that the object is in a lightweight locked state.

If the CAS operation fails, the virtual machine will first check whether the Mark Word of the object points to the virtual machine stack of the current thread. If so, it means that the current thread already owns the lock object, then it can go directly to the synchronization block to continue execution, otherwise the lock object has been preempted by other threads. If more than two threads compete for the same lock, the lightweight lock is no longer valid and is inflated to a heavyweight lock.

Bias lock

The idea of a lock bias is that it is biased towards the first thread that acquires the lock object, and then the thread acquires the lock without the need for synchronization or even a CAS operation.

When the lock object is first acquired by the thread, it enters a biased state and is marked as 1 01. At the same time, use the CAS operation to record the thread ID to the Mark Word. If the CAS operation is successful, the thread does not need to perform any synchronization operation every time it enters the lock-related synchronization block.

When another thread tries to acquire the lock object, the biased state ends and returns to the unlocked or lightweight locked state after unRevoke Bias.

At this point, the study of "how to optimize Java locks" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report