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 Volatile variable in Java

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail what is the use of the Volatile variable in Java. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The Volatile keyword is a lightweight synchronization mechanism provided by Java. The Java language contains two inherent synchronization mechanisms: synchronization blocks (or methods) and volatile variables. Volatile is lighter than synchronized (synchronized is often called a heavyweight lock) because it does not cause thread context switching and scheduling. But the volatile variable is less synchronized (sometimes simpler and less expensive), and its use is more error-prone.

1. The characteristic of volatile variable 1.1.The visibility is guaranteed, but the atomicity is not guaranteed.

When writing a volatile variable, JMM forcibly flushes the variables in the thread's local memory to the main memory.

This write operation will invalidate the volatile variable cache in other threads.

Let's look at a piece of code:

Public class Test {public static void main (String [] args) {WangZai wangZai = new WangZai (); wangZai.start (); for (;) {if (wangZai.isFlag ()) {System.out.println ("hello");}} static class WangZai extends Thread {private boolean flag = false Public boolean isFlag () {return flag;} @ Override public void run () {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} flag = true; System.out.println ("flag =" + flag) }}}

You will find that the hello code will never be output. If the thread changes the flag variable, the main thread can also access it.

But by decorating the flag variable with volatile, you can output the code hello

Private volatile boolean flag = false

When each thread manipulates the data, it will read the data from the main memory to its own working memory. If he manipulates the data and writes it, the variable copies of other read threads will be invalidated. The data needs to be manipulated and has to be read in the main memory again.

Volatile ensures the visibility of different threads on shared variable operations, that is, one thread modifies volatile-decorated variables, and when the changes are written back to main memory, the other thread immediately sees the latest value.

1.2. Prohibition of instruction rearrangement

Reordering requires following certain rules:

The reorder operation does not reorder operations that have data dependencies.

Reordering is to optimize performance, but no matter how reordered, the execution result of a single-threaded program cannot be changed.

What is reordering?

To improve performance, compilers and processors often reorder instructions in a given order of code execution.

What are the types of reordering?

A good memory model actually relaxes the shackles on processor and compiler rules, that is, both software and hardware technologies strive for the same goal: to improve execution efficiency as much as possible without changing the results of program execution.

JMM minimizes the constraints on the underlying layer so that it can give full play to its own advantages.

Therefore, when executing a program, compilers and processors often reorder instructions in order to improve performance.

General reordering can be divided into the following three categories:

Compiler-optimized reordering. The compiler can rearrange the execution order of statements without changing the semantics of a single-threaded program.

Instruction-level parallel reordering. Modern processors use instruction-level parallel technology to execute multiple instructions overlapped. If there is no data dependency, the processor can change the execution order of the statements corresponding to the machine instructions

Reordering of memory systems. Because the processor uses caching and read / write buffers, it appears that load and storage operations may be performed out of order.

So how does Volatile guarantee that it won't be reordered?

Memory Barrier

The java compiler inserts memory barrier instructions in place when generating a series of instructions to prevent reordering of certain types of processors.

In order to implement the memory semantics of volatile, JMM restricts certain types of compiler and processor reordering, and JMM establishes a table of volatile reordering rules for the compiler:

Can you reorder the second operation? the first operation is ordinary read / write volatile read volatile write ordinary read / write NOvolatile read NONONOvolatile write NONO

For example, the last cell in the third line means that in program order, when the first operation is a read or write of a normal variable, and if the second operation is volatile, the compiler cannot reorder these two operations.

We can see from the above table:

When the second operation is volatile write, no matter what the first operation is, it cannot be reordered. This rule ensures that operations before volatile writing are not reordered by the compiler after volatile writing.

When the first operation is a volatile read, no matter what the second operation is, it cannot be reordered. This rule ensures that operations after volatile read are not reordered by the compiler before volatile read.

When the first operation is volatile write and the second operation is volatile read, it cannot be reordered.

It is important to note that volatile writes insert memory barriers at the front and back respectively, while volatile reads insert two memory barriers at the back.

Write

Read

Starting from JDK5, the concept of happens-before is put forward to illustrate the memory visibility between operations.

III. Happens-before

Definition of happens-before relationship:

If one operation happens-before another operation, the execution result of the first operation is visible to the second operation.

If there is a happens-before relationship between the two operations, it does not mean that the specific implementation of the Java platform must be performed in the order specified by the happens-before relationship. If the result of execution after reordering is consistent with the result of execution according to the happens-before relationship, then JMM also allows for such reordering.

Seeing this, do you think that this is the same as the semantics of as-if-serial? Yes, happens-before relationships are essentially the same thing as as-if-serial semantics.

As-if-serial semantics ensures that the result of execution after reordering in a single thread is consistent with that of the program code itself.

The happens-before relationship ensures that the execution results of correctly synchronized multithreaded programs will not be changed by reordering.

To sum up: if operation A happens-before operation B, then what operation A does in memory is visible to operation B, whether they are in the same thread or not.

In Java, for happens-before relationships, there are the following rules:

Program order rules: each operation in a thread, happens-before any subsequent operations in that thread.

Monitor lock rule: unlock a lock, which is subsequently locked by happens-before.

Volatile variable rules: write to a volatile field, happens-before and any subsequent reads to the volatile domain.

Transitivity: if A happens-before B and B happens-before C, then A happens-before C.

Start rule: if thread An executes the operation ThreadB. Start () starts thread B, then thread A's ThreadB. Start () operates on any operation happens-before in thread B.

Join rule: if thread An executes the operation ThreadB. Join () and returns successfully, then any operation in thread B happens-before on thread A from ThreadB. The join () operation returned successfully.

This is the end of this article on "what is the use of Volatile variables 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, please share it out 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