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

Java interviewer's favorite volatile keyword

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

In the Java interview, the interviewer's favorite question is related to the volatile keyword. After many interviews, have you ever wondered why they like to ask questions about the volatile keyword so much? And for you, as an interviewer, will you also consider using the volatile keyword as an entry point?

Why do you like to ask volatile keyword?

Interviewers who like to ask volatile keywords have a certain background in most cases, because volatile as a starting point, you can cut into the Java memory model (JMM) at the bottom, and then into Java concurrent programming in the direction of concurrency. Of course, further investigation, the underlying operation of JVM, the operation of bytecode, singletons can be involved.

So there are ways for people who understand to ask questions. So, let's take a look at what the volatile keywords are designed to: memory visibility (JMM feature), atomicity (JMM feature), prohibition of instruction rearrangement, thread concurrency, difference from synchronized. If you dig deeper, it may involve bytecode, JVM and so on.

But fortunately, if you have studied the Wechat official account "Program New Horizon" JVM series of articles, the above knowledge is no longer a problem, the right should be reviewed. So, in the form of the interviewer's question, try to answer it without looking at the answer, and see how effective the study is. A series of deadly questions, let's go.

Interviewer: tell me about the features of the volatile keyword

Shared variables modified by volatile have the following two characteristics:

Ensures the memory visibility of different threads on the operation of the variable; forbids instruction reordering

The answer is very good, pointing out two major features of the volatile keyword. In view of these two major features continue to go deep.

Interviewer: what is memory visibility? Can you give me an example?

This question is related to the Java memory model (JVM) and its memory visibility features. Here, some of the previous series "detailed explanation of Java memory Model (JMM)" and "detailed explanation of principles related to Java memory Model" are sorted out and answered.

First of all, the memory model: the Java virtual machine specification attempts to define a Java memory model (JMM) to shield the memory access differences of various hardware and operating systems, so that Java programs can achieve consistent memory access on various platforms.

JMM

The Java memory model synchronizes the new value back to the main memory after variable modification, refreshes the variable value from the main memory before the variable is read, and uses the main memory as the transmission medium. Examples can be given to illustrate the process of memory visibility.

JMM

Local memory An and B have a copy of the shared variable x in main memory, with an initial value of 0. Thread A updates x to 1 after execution and stores it in local memory A. When thread An and thread B need to communicate, thread A first flushes the x = 1 value in local memory to main memory, and the x value in main memory becomes 1. Subsequently, thread B reads the updated x value in the main memory, and the x value of thread B's local memory becomes 1.

Finally, visibility: visibility means that when one thread modifies the value of a shared variable, other threads are immediately aware of the change.

This is true for both ordinary variables and volatile variables, except that the volatile variable ensures that the new values can be immediately synchronized to the main memory and refreshed from the main memory when in use, ensuring the visibility of the variables in multithreaded operations. Ordinary variables are not guaranteed.

Interviewer: when it comes to JMM and visibility, can you talk about other features of JMM?

We know that JMM has atomicity and orderliness in addition to visibility.

Atomicity means that an operation or series is uninterruptible. Even in the case of multiple threads, once the operation starts, it will not be interfered with by other threads.

For example, for a static variable int x to which two threads assign a value at the same time, thread An assigns a value of 1, while thread B assigns a value of 2. No matter how the thread runs, the final value of x is either 1 or 2. The operation between thread An and thread B is uninterrupted, which is atomic and uninterruptible.

In the Java memory model, orderliness can be summed up as follows: if you observe within this thread, all operations are ordered, and if you observe another thread in one thread, all operations are disordered.

Orderliness means that for single-threaded code execution, execution is carried out sequentially. However, in a multithreaded environment, disorder may occur because there will be "instruction rearrangement" in the compilation process, and the rearranged instructions may not be in the same order as the original instructions.

Therefore, the first half of the above sentence refers to the guarantee of serial semantic execution in the thread, and the second half refers to the phenomenon of "reproducing" image and "synchronous delay between working memory and main memory".

Interviewer: you have mentioned instruction rearrangement many times. Can you give me an example?

In order to improve the efficiency of program execution, CPU and compiler will optimize instructions according to certain rules. However, there is a certain sequence between the code logic, and different results will be obtained according to different execution logic when executing concurrently.

Give an example of possible rearrangements in multithreading:

Class ReOrderDemo {

Int a = 0

Boolean flag = false

Public void write () {a = 1; / 1 flag = true; / / 2} public void read () {if (flag) {/ / 3 int I = a * a; / / 4. }}

}

12345678910111213141516

In the above code, when executed with a single thread, the read method can get the value of flag to judge and get the expected result. However, in the case of multithreading, different results may occur. For example, when thread A performs a write operation, the order in which the code in the write method executes might look like this because of instruction rearrangement:

Flag = true; / / 2

A = 1; / 1

twelve

That is, it is possible to assign a value to flag and then to a. This does not affect the final output in a single thread.

But if, at the same time, the B thread is calling the read method, it is possible that flag is true but an is still 0, and the result of step 4 is 0 instead of the expected 1.

The variable modified by the volatile keyword will prohibit the operation of instruction rearrangement, thus avoiding the problem in multithreading to a certain extent.

Interviewer: can volatile guarantee atomicity?

Volatile guarantees visibility and orderliness (rearranging instructions is prohibited), so can atomicity be guaranteed?

Volatile cannot guarantee atomicity, it is only atomic for reading / writing to a single volatile variable, but it is not guaranteed for composite operations like I.

The following code, intuitively speaking, feels that the output is 10000, but there is no guarantee, just because the inc operation is a compound operation.

Public class Test {

Public volatile int inc = 0

Public void increase () {inc;} public static void main (String [] args) {final Test test = new Test (); for (int iTuno

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

Servers

Wechat

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

12
Report