In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the three ways of writing the synchronized keyword in java? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Preliminary knowledge
First, we need to know that there are three variables in java:
Instance variable = "exists in the heap
Static variable = "exists in the method area
Local variable = "exists in the stack
Then, we have to understand that it is appropriate to have high concurrency insecurity.
Condition 1: multithreading concurrency.
Condition 2: there is shared data.
Condition 3: the shared data has the behavior of modification.
For specific unsafe cases, please refer to the following article: detailed explanation of Java thread safety issues
In the case of bank withdrawals in the above article, our solution to the thread safety problem is to add a synchronized keyword. Next, we will introduce in detail the three writing methods of synchronized and what problems to solve respectively!
First, modify the code block package ThreadSafa; public class Test {public static void main (String [] args) {TestAccount ta1 = new TestAccount (); ta1.setNum (10); / / share an account object TestThread T1 = new TestThread (ta1); TestThread T2 = new TestThread (ta1); t1.start (); t2.start ();}} class TestThread extends Thread {private TestAccount mAccount Public TestThread (TestAccount mAccount) {this.mAccount = mAccount;} @ Override public void run () {mAccount.updateNum (1);}} class TestAccount {private double num; public double getNum () {return num;} public void setNum (double num) {this.num = num } public void updateNum (int n) {synchronized (this) {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} setNum (getNum ()-n);} System.out.println (getNum ());}}
Running result
Writing method 2: modification method package ThreadSafa; public class Test {public static void main (String [] args) {TestAccount ta1 = new TestAccount (); ta1.setNum (10); TestThread T1 = new TestThread (ta1); TestThread T2 = new TestThread (ta1); t1.start (); t2.start ();} class TestThread extends Thread {private TestAccount mAccount Public TestThread (TestAccount mAccount) {this.mAccount = mAccount;} @ Override public void run () {mAccount.updateNum (1);}} class TestAccount {private double num; public double getNum () {return num;} public void setNum (double num) {this.num = num } public synchronized void updateNum (int n) {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} setNum (getNum ()-n); System.out.println (getNum ());}}
Running result
Summary
As you can see, the previous two writing methods are actually equivalent, what does it mean? That is, when you use synchronized to decorate the shared object this, you can mention synchronized in front of the method, but we don't usually do this, because expanding the scope of synchronized-decorated code will make the code less efficient.
At the same time, the first two methods are born to solve the problem of thread safety of instance variables, how do we deal with static variables? Please look at the third way of writing:
Method 3: modify the static method package ThreadSafa; public class Test {public static void main (String [] args) {TestAccount ta1 = new TestAccount (); TestAccount ta2 = new TestAccount (); TestThread T1 = new TestThread (ta1); TestThread T2 = new TestThread (ta2); t1.start (); t2.start ();} class TestThread extends Thread {private TestAccount mAccount Public TestThread (TestAccount mAccount) {this.mAccount = mAccount;} @ Override public void run () {mAccount.updateCount (1);}} class TestAccount {private double num; public static double count = 10; public double getNum () {return num;} public void setNum (double num) {this.num = num } public synchronized void updateNum (int n) {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} setNum (getNum ()-n); System.out.println (getNum ());} public synchronized static void updateCount (int n) {try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();} count-= n; System.out.println (count);}}
Display of running results
As you can see, after adding synchronized to the static method, he locks this class. Although the two account objects are different, adding synchronized ensures that they queue up for execution, that is, thread safety.
Synchronized principle
Synchronized is implemented through a monitor lock (monitor) inside the object. But the monitor lock is essentially realized by the mutex (Mutex Lock) of the underlying operating system. The operating system needs to switch between threads, which requires a transition from user mode to core mentality, which is very expensive, and the transition between states takes a relatively long time, which is why Synchronized is inefficient. This kind of lock, which depends on the implementation of operating system mutex (Mutex Lock), is called "heavyweight lock".
1. Monitor locking process
The monitor is locked when it is occupied, and the thread attempts to take ownership of the monitor when it executes the monitorenter instruction, as follows:
A. If the entry number of the monitor is 0, the thread enters the monitor, and then sets the entry number to 1, which is the owner of the monitor.
B. If the thread already owns the monitor and just re-enters, the number of entries into the monitor is increased by 1.
C. If another thread has already occupied the monitor, the thread enters a blocking state until the number of entries to the monitor is 0, and then retries to take ownership of the monitor.
2. Synchronized lock
After Java SE1.6 has made various optimizations to Synchronized, it is not so heavy. Different lock optimizations are introduced in different scenarios.
1. Biased locks: suitable for cases where there is no competition for locks, assuming that shared variables are accessed by only one thread. If there are other threads competing for the lock, the lock expands into a lightweight lock.
two。 Lightweight locks: suitable for locks with multiple threads competing, but there is no competition for locks in a synchronous method block cycle, and if other threads compete for locks during the synchronization cycle, the lock expands to a heavy lock.
3. Heavyweight locks: use heavyweight locks when competition is fierce.
Biased locks and lightweight locks have a performance weight lock because it is good, essentially because biased locks and lightweight locks only use CAS.
3. Synchronized lock optimization
Try to use lightweight locks and biased locks to optimize Synchronized, but these two locks are not completely without shortcomings. For example, when the competition is fierce, not only can not improve the efficiency, but will reduce the efficiency, because there is one more lock upgrade process, at this time, you need to use-XX:-UseBiasedLocking to disable biased locks.
Summary
Local variable = "exists in stack =" cannot be shared between threads = "so data is always safe
Instance variable = "exists in the heap =" can be shared between threads = "using writing methods 1 and 2 to ensure thread safety
Static variable = "exists in method area =" can be shared between threads = "use square writing method 3 to ensure thread safety
This is the answer to the question about what are the three ways to write the synchronized keyword in java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.