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 editor will give you a detailed explanation of Volatile.

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

The shared variable modified by the volatile keyword has two main characteristics: 1. Ensures the memory visibility accessed by different threads 2. Prohibit reordering

Before talking about memory visibility and orderliness, it is necessary to take a look at Java's memory model (note the distinction between the JVM memory model and the memory model)

Why is there a java memory model?

First of all, we know that there is a great difference in the execution speed between memory access and CPU instructions, which is not an order of magnitude at all. in order to reduce the gap between java running on various platforms, which processor bosses have added various caches on CPU to reduce the speed gap between memory operations and CPU instructions. While Java carries out a wave of abstraction at the java level, the java memory model divides memory into working memory and main memory, each thread from the main memory load data to the working memory, assigns the load data to the variables on the working memory, and then the corresponding thread of the working memory carries out processing, the processing result is assigned to its working memory, and then assigns the data to the variables in the main memory (this time requires a graph).

The editor will give you a detailed explanation of Volatile.

The editor will give you a detailed explanation of Volatile.

The use of working memory and main memory speeds up processing, but it also brings some problems, such as the following example

1 int I = 1

2 I = iFig 1

When in the case of a single thread, the final value of I must be 2; but in the case of two threads, must it be 3? Not necessarily. When thread A reads the value of I to its working memory, CPU switches to thread B, and thread B reads that the value of I is also 1, then adds 1 to 1 and then save to main memory, thread An also adds 1 to I and save back to main memory, but in the end the value of I is 2. If the write operation is slow, the value you read may still be 1, which is the problem of cache inconsistency. JMM is built around atomicity, memory visibility and ordering. The problem of cache inconsistency is solved by solving these three features. Volatile focuses on memory visibility and orderliness.

Atomicity

Atomicity means that an operation either succeeds or fails, and there is no intermediate state, such as ioperations 1, which directly reads the value of I, which must be an atomic operation; but iatomicity, which seems to be, actually needs to read the value of I first, then + 1, and finally requires three steps in assigning a value to I, which is not an atomic operation. In JDK1.5, the atomic classes AtomicBoolean, AtomicLong and AtomicInteger corresponding to boolean, long and int are introduced, and they can provide atomic operations.

Memory visibility

After a variable with memory visibility is modified by a thread, it is immediately flushed to main memory and invalidates data on the cache rows of other threads.

The variable modified by volatile has memory visibility, which is mainly shown as follows: when writing a volatile variable, JMM will immediately flush the shared variable in the working memory corresponding to the thread to the main memory; when reading a volatile variable, JMM will set the value in the working memory corresponding to the thread to invalid and then read from the main memory, but if no thread modifies the shared variable, the operation will not be triggered.

Order

JMM allows processors and compilers to reorder instructions, but specifies as-if-serial, which means that no matter how much you reorder, the end result is the same. For example, the following code:

1 int weight = 10; / / A

2 int high = 5; / / B

3 int area = high weight high; / / C

This code can be executed according to Amure-> Bmurf-> C, or BMY-> Amure-> C, because An and B are independent of each other, while C depends on An and B, so C cannot rank before An or B. JMM guarantees single-threaded reordering, but it is prone to problems in multithreading. For example, in the following situation

The editor will give you a detailed explanation of Volatile.

The editor will give you a detailed explanation of Volatile.

1 boolean flag = false

2 int a = 0

4 public void write () {

5 int a = 2; / / 1

6 flag = true; / / 2

7}

8 public void multiply () {

9 if (flag) {/ / 3

10 int ret = a * a; / / 4

11}

12}

The editor will give you a detailed explanation of Volatile.

The editor will give you a detailed explanation of Volatile.

If there are two threads executing the above code, thread 1 executes the write method first, and then thread 2 executes the multiply method. Does it have to be 4 in the end? not necessarily.

The editor will give you a detailed explanation of Volatile.

The editor will give you a detailed explanation of Volatile.

As shown in the figure, JMM reorders 1 and 2, first setting flag to true, which is executed by thread 2, and because a has not yet been assigned, the final value of ret is 0

If you use the volatile keyword to modify flag and disable reordering, you can ensure the orderliness of the program, or you can use heavy-level locks such as synchronized or lock to ensure orderliness, but the performance will degrade.

In addition, JMM has some innate orderliness, that is, orderliness that can be guaranteed without any means, which is often called the happens-before principle. The following happens-before rules are defined:

The first rule of program order is that in a thread, all operations are in order, but in JMM, as long as the execution results are the same, reordering is allowed. Happens-before here also emphasizes the correctness of single-thread execution results, but there is no guarantee that multithreading is the same.

Rule 2 the monitor rule is also easy to understand, that is, before the lock is added, it is determined that the lock has been released before the lock can be continued.

The third rule applies to the volatile in question. If one thread writes a variable first and then another thread reads it, then the write operation must precede the read operation.

The fourth rule is the transitivity of happens-before.

It is important to note that shared variables modified by volatile only satisfy memory visibility and prohibit reordering, and do not guarantee atomicity. For example, volatile iTunes +.

The editor will give you a detailed explanation of Volatile.

The editor will give you a detailed explanation of Volatile.

1 public class Test {

2 public volatile int inc = 0

4 public void increase () {

5 inc++

6}

8 public static void main (String [] args) {

9 final Test test = new Test ()

10 for (int idol.

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

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report