简体   繁体   English

类成员变量需要Java“volatile”?

[英]Java “volatile” needed for class member variables?

I have a question regarding the Java "volatile" keyword:我有一个关于 Java “volatile” 关键字的问题:

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:现在,假设一个线程正在使用这个带有“volatile”关键字的类:

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"?我是否必须将“volatile”关键字也附加到“BooleanValClass”类的成员字段“bolVal”,还是对象的“volatile”引用某种“重定向”到“BooleanValClass”类的所有成员?

Thanks, Tom谢谢,汤姆

Nothing is redirected.什么都没有重定向。 myClass is volatile, bolVal is not. myClass是 volatile, bolVal不是。 Assignments and reads from myClass work as volatile.myClass分配和读取的工作是不稳定的。 Assignments/reads to/from bolVal don't.bolVal分配/读取不是。

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.在 Java 中,除了 long 和 double 之外的所有类型的字段都由 JVM 原子地发生,如果该字段用 VOLATILE 修饰符声明,那么即使 long 和 double 也会被原子地读写。 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.原子保证,我们可以 100% 获得变量中的内容,或者变量中将计算的内容,变量中也不可能有任何中间结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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