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 use of locking mechanisms synchronized and CAS in Java

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

Share

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

This article is to share with you about the usefulness of locking mechanisms synchronized and CAS in Java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

First, why do you use locks?

We definitely use multithreading to improve efficiency and squeeze the performance of hardware to improve efficiency, assuming that one more thread is equivalent to one more person to work, but sometimes more people are not easy to manage, and problems may occur.

For example, I am now working on a multi-threaded demo. My original intention is that every thread shouts "ZPNB!" I wrote down the following code.

Public class ThreadDemo implements Runnable {@ Test public void testThread () {System.out.println ("tell me out loud:"); ThreadDemo demo = new ThreadDemo (); Thread threadOne = new Thread (demo, "Zhang San: ZPNB"); Thread threadTwo = new Thread (demo, "Li Si: ZPNB"); Thread threadThree = new Thread (demo, "Wang er Mazi: ZPNB"); Thread threadFour = new Thread (demo, "Zhao Si: ZPNB") ThreadOne.start (); threadTwo.start (); threadThree.start (); threadFour.start ();} @ Override public void run () {/ / synchronized (this) {for (int I = 0; I)

< 10 ;i++ ){ try { System.out.println(Thread.currentThread().getName()); //这里设置0是因为Junit的限制你设置长了,他就执行一段时间就不执行了 Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); } }// } } 没有加锁的情况是这样的,看起来很乱我希望他们每个人都喊十遍然后下一个人,显然下面的结果不满意 大声告诉我:李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB张三:ZPNB李四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB王二麻子:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB赵四:ZPNB王二麻子:ZPNB 但是如果我把synchronized的注释取消就变成了我想要的依次每人喊十遍 大声告诉我:张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB张三:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB赵四:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB王二麻子:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB李四:ZPNB 这就突出了锁的重要性,我们希望有些线程能按照我们希望的一个顺序依次来执行,而不是先到先得的。 二 synchronized怎么实现的 实际上每一个对象实际都拥有一个叫做监视器monitor的东西,线程只有获得了这个监视器才能才能进入同步块和同步方法,如果没有获取到监视器的线程将会被阻塞在同步块和同步方法的入口处,具体过程如下图:

Well, what if you don't get the monitor? if there's something in the synchronous queue, just wait until the last exit that gets the monitor launches the monitor, and then you get it according to the queue order. Of course, you may encounter a "newcomer" who doesn't enter the queue to grab it directly with you in the process of re-acquisition. If you haven't robbed it yet, you have to repeat the previous waiting process.

In fact, there is also the concept of "happen before" of a lock ("A hapen-bfore B, then the result of An is visible to B"), that is, if the previous thread rewrites some values, the latter principle should be rewritten on this basis, suppose a calculation program, the values have changed, the new thread you are still taking the original value to calculate, it should be on the new value to do the operation. In this way, multithreaded collaboration makes practical sense.

The following is about the scope of synchronized (basically actual objects or class objects, if you are class objects, then how many instance objects of your new are still locked. )

Who comes the third CAS?

The concept of CAS suddenly emerged as an implementation of thread safety, so what is the relationship between it and synchronized?

In fact, the two should be the concept of the same level, everyone is a lock, synchronized is a pessimistic lock, basically a thread is locked, blocking synchronization. It is considered that any operation may be a conflict, so in the worst-case scenario, thread contention blocks, and blocking ends wakes up the blocked process.

CAS is compare and swap, which is not locked directly, which roughly means:

CAS contains three values: the actual value stored in the V memory address; the expected value of O (the old value); and the new value of N update. When V and O are the same, that is, the same old value as the actual value in memory indicates that the value has not been changed by other threads, that is, the old value O is the latest value so far, and it is natural to assign the new value N to V. On the contrary, V and O are different, indicating that the value has been changed by other threads, then the old value O is not the latest version of the value, so you can not assign the new value N to V, just return V. When multiple threads use CAS to manipulate a variable, only one thread will succeed and update successfully, and the rest will fail. The failed thread will try again, or you can choose to suspend the thread.

CAS is relatively gentle for thread contention conflicts. He will have his own retry mechanism, but not this time. I'll check it out later, rather than blocking the pending and wake-up state, which is too time-consuming.

In the Java.util,ConCurrent package, many people use CAS to deal with synchronization problems, rather than directly decorating it with a synchronized.

Which is better, four synchronized or CAS?

In fact, from now on, it is really hard to say, because in CAS's proposal, synchronized is also making continuous progress. It can't be said that CAS is better than synchronized.

For example, CAS also has its own problems, the most important of which are: ABA, excessive spin time and atomic operations that guarantee only one shared variable, although they all require related solutions:

(1) ABA is two threads, the first thread changes the initial A value to B and then A, and the second thread takes over the direct CAS, it will not get the previous conversion process, and the solution is the same as the database plus a version number 1A 2B 3C solution.

(2) too long spin time is a thread competition conflict, keep retrying, it is actually a loop operation, this cycle may have to wait a long time, resulting in the so-called spin time is too long.

(3) if you can only manipulate one shared atom, turn the atom into an object and stuff everything you want to share.

Synchronized itself is constantly optimizing itself, even borrowing from CAS's ideas in 1. 6. In order to reduce the performance consumption caused by acquiring and releasing locks, "biased lock" and "lightweight lock" are introduced. In Java SE 1.6, there are four kinds of locks, and the levels from low to high are: no lock state, bias lock state, lightweight lock state and heavy lock state.

Biased lock (look at the thread ID in the object header and stack frame through the thread ID (the recorded thread ID is the biased thread ID), and get the thread that does not try CAS to set itself as biased)

The details are as follows:

When a thread accesses the synchronous block and acquires the lock, the thread ID of the lock bias is stored in the lock record in the object header and stack frame. Later, the thread does not need to lock and unlock the synchronized block when entering and exiting the block. It is simply necessary to test whether the biased lock pointing to the current thread is stored in the Mark Word of the object header. If the test is successful, the thread has acquired the lock. If the test fails, you need to test again whether the identity of the biased lock in Mark Word is set to 1 (indicating that it is currently biased), if not, the CAS contention lock is used; if so, try to use CAS to point the biased lock of the object header to the current thread.

Lightweight lock

(the pointer of the replacement lock replaces the achievement to get the lock, the replacement does not achieve the spin cycle to find the opportunity to replace)

The details are as follows:

Before the thread executes the synchronization block, JVM creates a space to store the lock record in the stack frame of the current thread and copies the Mark Word in the object header to the lock record. The thread then attempts to use CAS to replace the Mark Word in the object header with a pointer to the lock record. If successful, the current thread acquires the lock, and if it fails, it indicates that other threads are competing for the lock, and the current thread attempts to acquire the lock using spin.

Weight lock

The implementation of monitor monitor lock is the heaviest step, because it involves switching between user mode and system state. )

Heavyweight locks are implemented by relying on monitor locks within the object. When the system checks that the lock is a heavyweight lock, it blocks the thread waiting for the lock to be acquired, and the blocked thread does not consume cup. But when blocking or waking up a thread, you need the help of the operating system, you need to transition from the user mode to the kernel state, and the transition state takes a lot of time.

In this way, synchronized is not so unbearable, and what you implement in CAS is not necessarily better than the "veteran" synchronized in some environments.

Thank you for reading! This is the end of this article on "what is the use of synchronized and CAS in Java?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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