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

The function and implementation principle of Volatile keyword of Java

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

Share

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

This article mainly explains "the function and implementation principle of the Volatile keyword of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the function and implementation principle of Java's Volatile keyword".

Volatile action

Volatile plays an important role in concurrent programming, and volatile is a lightweight synchronized,volatile keyword that serves two purposes:

1) ensure the visibility of shared variables

Visibility means that when one thread modifies a shared variable, another thread can read the modified value. In a previous article, Java concurrent programming: the Java memory model JMM said that there is a difference between the main memory and the local memory in the Java memory model, and the local memory holds a copy of the shared variable, and the thread modifies the shared variable first by modifying the copy of the local memory, and then writing back to the main memory.

There may be a situation in which thread An and thread B modify a shared variable C at the same time, assuming that thread A first modifies the shared variable C, while thread B fails to perceive that the shared variable C has changed in time. Then B modifies the local expired copy data, which causes the invisibility of the shared variable.

On the other hand, the shared variable modified by the volatile keyword will be refreshed to the main memory immediately after the thread modifies the shared variable, and will invalidate the data cached by other threads, which ensures the visibility of the shared variable between threads.

2) prevent instruction reordering

Another function of the volatile keyword is to prevent instruction reordering. In the actual execution process, the code is not all executed in the order in which it is written. Under the condition that the result of single-thread execution remains unchanged, the compiler or CPU may reorder the instructions to improve the execution efficiency of the program. However, in the case of multithreading, instruction reordering may cause some problems, the most common of which is the double check lock singleton mode:

Public class SingletonSafe {private static volatile SingletonSafe singleton; private SingletonSafe () {} public static SingletonSafe getSingleton () {if (singleton = = null) {synchronized (SingletonSafe.class) {if (singleton = = null) {singleton = new SingletonSafe ();} return singleton;}}

If you do not use the volatile keyword, there may be other threads to get an uninitialized singleton object, the specific reason the author will not repeat here, interested students can search for "double checked locking with delay initialization" study, the author has time to write an article analysis later.

Volatile implementation principle 1) visibility implementation principle

For variables modified by the volatile keyword, when writing to the volatile variable, JVM sends an instruction with a lock prefix to the processor to write back the variable in the cache to the system main memory. But even if it is written back to memory, if the cache values of other processors are still old, it will be a problem to perform computing operations, so in multiprocessors, in order to ensure that the cache of each processor is consistent, the cache consistency protocol will be implemented.

Cache consistency protocol: each processor checks whether its cache value has expired by sniffing the data propagated on the bus. When the processor finds that the memory address of its cache line has been modified, the cache line of the current processor will be set to an invalid state, and when the processor wants to modify this data, it will force the data to be re-read from the system memory to the processor cache.

Therefore, if a variable is modified by volatile, its value will be forced to be brushed into main memory after each data change. The cache of other processors will also load the value of this variable from the main memory into their own cache because they comply with the cache consistency protocol. This ensures that the value of a volatile is visible in multiple caches in concurrent programming.

2) the implementation principle of preventing instruction reordering

Volatile prevents instruction reordering through the memory barrier. There are three types of memory barriers:

Store Barrier

The Store barrier, the x86 "sfence" instruction, forces all store instructions that precede the store barrier instruction to be executed before the store barrier instruction is executed.

Load Barrier

The Load barrier, the "ifence" instruction on x86, forces all load instructions after the load barrier instruction to be executed after the load barrier instruction is executed.

Full Barrier

The Full barrier, which is the "mfence" instruction on x86, combines the functions of load and save barriers.

In the Java memory model, the volatile variable inserts a store barrier after the write operation and a load barrier before the read operation. The final field of a class inserts a store barrier after initialization to ensure that the final field is visible when the constructor initialization is complete and can be used. It is JMM that inserts memory barrier instructions before and after reading and writing volatile variables, thus ensuring the sequential execution of instructions.

At this point, I believe you have a deeper understanding of "the function and implementation principle of the Volatile keyword of Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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