After using the volatile variable, which one conforms to the happens-before rule?

public class TestClass {

int i = 0;
volatile boolean tmpvo = false;
public void one() {
    i = 1; // 
    tmpvo = true; // 
}
public void two() {
    if(tmpvo) { // 
        int j = i; // 
        //......
    }
}

}
suppose that after the one () method is executed by thread 1, the method two () is executed by thread 2. Which of the following conforms to the rules of happens-before? Radio
A, integer variable happens-before assignment operation
B, Boolean variable happens-before judgment operation
C, integer variable happens-before Boolean variable
D, judgement operation happens-before assignment operation

Mar.29,2021

I should choose C


I choose D. the integer and Boolean variables in a single thread may be reordered and have no effect on them, while volatile is the concurrency guarantee of multithreading, ensuring visibility, so I choose to judge and assign logically


is obviously B. Isn't that what volatile does


volatile variable write operation happen-before read operation, select B


in addition, Java's in-memory model has some inherent ordering rules that can be guaranteed without any Synchronize means, which is called the Happens-before principle. If the execution order of two operations cannot be deduced from the happens-before principle, then they cannot guarantee ordering, which means that the virtual machine or processor can reorder them at will.
Let's take a look at the happens-before principles in detail.
Program order rules: within a thread, the code is executed in the order in which it was written, and the later actions occur after the previous actions are written.
volatile variable rule: write to a variable is earlier than read to that variable.
.

excerpt from "detailed explanation of Java High concurrency programming: multithreading and Architecture Design"-Wang Wenjun

Menu