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

What is the function of the synchronized keyword in Java

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail what is the role of synchronized keywords in Java. The quality of the article is high, so Xiaobian shares it with you as a reference. I hope you have a certain understanding of related knowledge after reading this article.

1. What is synchronized We understand it as a synchronous lock, which can achieve synchronous access to shared resources and solve the security problem of thread concurrency. 1.1 How to use the modified instance method, act on the current object instance lock, before entering the synchronization code to obtain the lock of the current object instance Modified static method, act on the current class object lock, before entering the synchronization code to obtain the lock of the current class object. That is to say, locking the current class will affect all object instances of the class, because static members do not belong to any instance object, but are class members (static indicates that this is a static resource of the class, no matter how many objects are new, only one, so all objects of the class are locked). So if thread A calls a non-statically synchronized method of an instance object, and thread B needs to call a statically synchronized method of the class to which the instance object belongs, mutual exclusion does not occur, because accessing the statically synchronized method occupies the lock of the current class, and accessing the non-statically synchronized method occupies the lock of the current instance object. Modifies a block of code to specify a locked object, locks the given object, and acquires the lock of the given object before entering a synchronized block. Just like synchronized methods, synchronized(this) blocks lock the current object. The synchronized keyword is added to static methods and synchronized(class) blocks to lock the Class class. Here again: the synchronized keyword is added to a nonstatic static method to lock an object instance. Another thing to note is: try not to use synchronized(String a) because in the JVM, the string constant pool has a buffering function! 2. Early synchronizedJDK1.6 before belonging to heavyweight locks, dependent on the operating system Mutex Lock, Java thread mapping to the operating system's native threads, the operating system needs to apply for mutual exclusion, the operating system to switch threads, need to switch from user state to kernel state, more time-consuming, low efficiency. 3. After JDK 1.6, a lot of optimizations have been made to the synchronized bottom layer at the JVM level, including biased locking, lightweight locking, spin locking, adaptive spin locking, lock cancellation, lock coarsening and other optimization techniques. 3.1 Biased locking purpose: reduces the overhead of traditional heavyweight locks using operating system mutexes and improves performance without thread contention. Features: In the case of no lock contention, the entire lock will be eliminated in favor of the first thread to acquire the biased lock. If the biased lock is not acquired by other threads in the subsequent execution, then the thread that owns the lock does not need to change synchronously: In the case of fierce lock contention, the biased lock is invalid. The reason is that, in this case, it is very likely that the thread requesting the lock is not the same thread each time, so biased locks should not be used at this time, otherwise the loss is not worth it. However, when biased locks fail, they do not immediately expand to heavyweight locks, but are first upgraded to lightweight locks. For more information on how biased locking works, see Chapter 13, Lock Optimization, in Understanding the Java Virtual Machine: Advanced JVM Features and Best Practices, 2nd Edition. 3.2 Lightweight locks When biased locks fail, the JVM does not immediately upgrade to heavyweight locks, but instead attempts to use lightweight lock optimizations (added after JDK 1.6). Lightweight locks are not intended to replace heavyweight locks. They are intended to reduce the overhead of traditional heavyweight locks using operating system mutexes and improve performance without thread contention. Purpose: Same as bias lock Features: Unlike bias lock, lightweight lock uses CAS operation instead of heavyweight lock. With lightweight locks, there is no need to apply for mutex. Locking and releasing lightweight locks are CAS operations. Variation: For most locks, there is no contention throughout the synchronization cycle, which comes from empirical data. If there is no contention, lightweight locks use CAS operations, avoiding the overhead of using mutex locks. If there is contention, there are additional CAS operations in addition to the overhead of mutex locks, so lightweight locks are slower than heavyweight locks if there is contention. Lightweight locks can quickly swell into heavyweight locks if competition is fierce. For more information on how lightweight locks work, see Chapter 13, Lock Optimization, in Understanding the Java Virtual Machine: Advanced JVM Features and Best Practices, 2nd Edition. 3.3 After spinlocks and adaptive spinlocks lose their lightweight locks, the JVM prevents threads from actually hanging at the operating system level and performs an optimization called spinlocks. This technology existed before JDK 1.6, but it was turned off by default and can be turned on by the parameter--XX:+UseSpinning. After JDK 1.6, it is enabled by default. Spinning cannot completely replace blocking because it also takes up processor time. If the lock is occupied for a short time, then spin locks work well; otherwise, vice versa. Spin must wait for a fixed amount of time, and if it fails to acquire the lock beyond a limit, it suspends the thread. Spin defaults to 10 times and can be modified using the parameter--XX:PreBlockSpin. 3.3.1 Why there are spin-lock mutex synchronization The biggest impact on performance is the implementation of blocking, because the suspension and resumption of threads need to be transferred to kernel state to complete (the transition from user state to kernel state will take some time). Threads don't usually hold locks for long, and suspending or resuming threads just for that amount of time is not worth it. So the JVM team thought,"Can we make the next thread that requests the lock wait a while without getting hung up? See if the thread holding the lock will release it soon." Purpose: To reduce thread suspension and resumption and reduce overhead, spinlocks are introduced. 3.3.2 How to spin In order to make a thread wait, we only need to make the thread execute a busy loop (spin). This technique is called spinning. 3.3.3 Features of spin Fixed number of busy spin cycles performed (default 10 times) JDK 1.6 before the default off, after the default on the effect depends on the length of time the lock is occupied 3.3.4 Adaptive spin lock In addition, in JDK 1.6 introduced adaptive spin lock. Improvement: The number of spins is not fixed. The spin count is determined by the last spin count of the same lock and the state of the lock owner. JVMs are getting smarter. The difference from spin locks is that the number of spins is not fixed. 3.4 Lock elimination Even if the JVM is running, lock elimination is performed if it detects that there is no possibility of contention for shared data. This will save time on meaningless lock requests. 3.5 Lock coarsening principle we write code, always recommend synchronized code block scope limit as small as possible, only in the actual scope of shared data synchronization, so that the number of operands to be synchronized as small as possible, if there is competition, waiting thread will also get the lock as soon as possible. In most cases, the above principle is fine, but if a series of consecutive operations repeatedly lock and unlock the same object, it will introduce unnecessary performance consumption.

Synchronized vs ReenTrantLock Both are reentrant locks Both are reentrant locks The concept of a reentrant lock is that you can acquire your own internal lock again. For example, if a thread obtains a lock on an object, the lock has not been released yet. When it wants to obtain the lock of the object again, it can still obtain it. If the lock cannot be re-entered, it will cause deadlock. Each time the same thread acquires a lock, the lock counter increments by 1, so you have to wait until the lock counter drops to zero before releasing the lock.② synchronized depends on JVM and ReenTrantLock depends on APIsynchronized is dependent on JVM implementation, we also mentioned that the virtual machine team in JDK1.6 for synchronized keyword for a lot of optimization, but these optimizations are implemented at the virtual machine level, and not directly exposed to us. ReenTrantLock is implemented at the JDK level (i.e. API level, requires lock() and unlock methods with try/finally blocks), so we can see how it is implemented by looking at its source code.③ ReenTrantLock adds some advanced features compared to synchronized. There are three main points: a. Waiting can be interrupted;b. Fair locking can be implemented;c. Selective notification can be implemented (locks can be bound to multiple conditions) ReenTrantLock provides a mechanism to interrupt threads waiting for locks, through lock.lockInterruptibly() to implement this mechanism. This means that the waiting thread can choose to give up waiting and handle something else instead. ReenTrantLock can specify whether the lock is fair or unfair. Synchronized can only be an unfair lock. The so-called fair lock is that the thread that waits first gets the lock first. ReenTrantLock is unfair by default, and fairness can be determined by the ReentrantLock(boolean fair) constructor of the ReenTrantLock class. The synchronized keyword can be combined with wait() and notify/notifyAll() methods to implement the wait/notification mechanism, and the ReentrantLock class can of course be implemented, but with the help of the Condition interface and newCondition() method. Condition is only available after JDK1.5. It has good flexibility. For example, it can realize multi-channel notification function, that is, multiple Condition instances can be created in a Lock object (i.e., object monitor), thread objects can be registered in the specified Condition, so that thread notification can be selectively carried out, and more flexibility can be achieved in scheduling threads. When notifying using notify/notifyAll() method, the notified thread is selected by JVM. Using ReentrantLock class in combination with Condition instance can realize "selective notification". This function is very important, and it is provided by default of Condition interface. The synchronized keyword is equivalent to only one Condition instance in the entire Lock object, and all threads are registered on it. If the notifyAll() method is executed, it will notify all waiting threads, which causes a big efficiency problem, while the signalAll() method of the Condition instance will only wake up all waiting threads registered in the Condition instance. If you want to use the above features, then ReenTrantLock is a good choice. 4 Performance is no longer the selection standard Before JDK 1.6, synchronized performance was much worse than ReenTrantLock. The synchronized keyword throughput drops dramatically as the number of threads increases. ReenTrantLock basically maintains a relatively stable level. I think this also reflects the side, synchronized keyword there is a very large room for optimization. Subsequent technical developments have also proved this point, and we also talked about how the JVM team has done a lot of optimization for the synchronized keyword since JDK 1.6. After JDK 1.6, the performance of synchronized and ReenTrantLock is basically the same. So those articles on the Internet that say ReenTrantLock is selected because of performance are all wrong! After JDK 1.6, performance is no longer a factor in choosing synchronized and ReenTrantLock! Moreover, virtual machines will be more inclined to native synchronization in future performance improvements, so it is recommended to give priority to using the synchronized keyword for synchronization if synchronized can meet your needs! Optimized synchronized, like ReenTrantLock, uses CAS operations in many places.

What is the role of synchronized keyword in Java to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

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

Internet Technology

Wechat

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

12
Report