简体   繁体   中英

Java “volatile” needed for class member variables?

I have a question regarding the Java "volatile" keyword:

Assume, we have the following Class:

public class BooleanValClass {

    private boolean bolVal = false;

    public boolean getVal() {
        return this.bolVal;
    }

    public void setVal(boolean val) {
        bolVal = val;
    }
}

Now, assume a Thread is using this class with a "volatile" keyword:

private volatile BooleanValClass myClass = new BooleanValClass();

Do i have to attach the "volatile" keyword also to the member field "bolVal" of class "BooleanValClass" or is the "volatile" of the object reference some kind of "redirected" to all members of the class "BooleanValClass"?

Thanks, Tom

Nothing is redirected. myClass is volatile, bolVal is not. Assignments and reads from myClass work as volatile. Assignments/reads to/from bolVal don't.

In Java reading and writing fields of all types except long and double occurs atomically by JVM, and if the field is declared with the VOLATILE modifier, even long and double are become read and written atomically. Atomic garantee, that we get 100% either what was in variable, or what will calculated in variable, nor can there be any intermediate result in the variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM