In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail what is the use of the volatile keyword in Java, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
Overview
The keyword volatile in Java language is called lightweight synchronized. Compared with synchronized, volatile coding is relatively simple and runs with less overhead, but it is not so easy to use volatile correctly and reasonably, because it is more error-prone than using locks. Next, this paper mainly introduces the guidelines for the use of volatile and the points that should be paid attention to in the process of use.
Why use volatile?
(1) simplicity: it is easier to use volatile variables than locks in some scenarios that require synchronization.
(2) performance: in some cases, the performance of volatile synchronization mechanism is better than that of locks.
(3) volatile operations will not cause blocking as easily as locks.
Volatile characteristics
(1) the volatile variable has the visibility feature of synchronized, and if a field is declared as the volatile,java thread memory model, ensure that all threads see the same value of the variable.
(2) instruction reordering is prohibited
(3) atomicity is not guaranteed.
Note:
① reordering: reordering is usually a means of reordering instructions used by the compiler or runtime environment to optimize program performance.
② atomicity: an uninterruptible operation or series of operations
③ visibility: locks provide two main features: mutexes and visibility, that is, mutexes allow only one thread to hold a particular lock at a time, so you can use this feature to implement a coordinated access protocol for shared data so that only one thread can use the shared data at a time. The visibility is more complex, and it must ensure that changes made to the shared data before releasing the lock are visible to another thread that subsequently acquires the lock.
The realization principle of volatile
If you write to a variable that declares volatile, JVM sends an instruction with a Lock prefix to the processor. The Lock instruction will write the data of the cache line of the variable back to system memory. According to the cache consistency protocol, each processor will check whether its cache value has expired by sniffing the data transmitted on the bus. When the processor finds that the corresponding address of its cache line has been modified. The cache line of the current processor is set to an invalid state, and cache line padding is enforced the next time the same memory address is accessed.
Scenarios in which volatile is used correctly
Volatile is mainly used to solve the problem of invisible memory in multithreaded environment. For write-and-read, you can solve the variable synchronization problem, but if you write more, you can't solve the thread safety problem. Such as:
1. Scenarios that are not suitable for using volatile (non-atomic operations)
(1) counterexamples
Private static volatile int nextSerialNum = 0th public static long generateSerialNum () {return nextSerialNum++;}
The purpose of this method is to ensure that each call returns a different self-increment, but the result is not ideal. The problem is that the incremental operator (+ +) is not an atomic operation. In fact, it is a combined operation consisting of a sequence of read-modify-write operations. If the second thread reads the field during the first thread reads the old value and writes back the new value, the second thread and the first thread will read the same value.
(2) positive examples
In fact, faced with the above counterexample scenario, you can use the atomic wrapper type provided in JDK1.5 java.util.concurrent.atomic to ensure atomic operation.
Private static AtomicInteger nextSerialNum = new AtomicInteger (0); public static long generateSerialNum () {return nextSerialNum.getAndIncrement ();}
2. Scenarios suitable for using volatile
In daily work, volatile is mostly used in the scenarios of status flags, such as:
A scenario in which one thread terminates another thread
(1) counterexamples
Private static boolean stopThread;public static void main (String [] args) throws InterruptedException {Thread th = new Thread (new Runnable () {@ Override public void run () {int I = 0; while (! stopThread) {ionization;}); th.start (); TimeUnit.SECONDS.sleep (2); stopThread = true;}
After running, it is found that the program cannot terminate the loop at all, because the java language specification does not guarantee that the values written by one thread are visible to another thread, so even if the main function of the main thread modifies the state of the shared variable stopThread, it is not necessarily visible to the th thread, and the final loop may not be terminated.
(2) positive examples
Private static volatile boolean stopThread;public static void main (String [] args) throws InterruptedException {Thread th = new Thread (new Runnable () {@ Override public void run () {int I = 0; while (! stopThread) {ionization;}); th.start (); TimeUnit.SECONDS.sleep (2); stopThread = true;}
By modifying the shared variable stopThread with the keyword volatile, according to the visibility principle of volatile, it is guaranteed that the main thread main function modifies the shared variable stopThread state to be immediately visible to the thread th, so the thread th will stop the loop within two seconds.
About what the volatile keyword in Java is useful to share here, I hope the above content can be of some help to you, 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.
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.