Can volatile variable be defined as static in java?

后端 未结 5 1459
無奈伤痛
無奈伤痛 2021-02-01 04:36

Can I declare something like this??

static volatile boolean first=false;
5条回答
  •  生来不讨喜
    2021-02-01 05:05

    Yes, you can.

    A static variable in Java is stored once per class (not once per object, such as non-static variables are). This means all your objects (and static methods) share the same variable.

    Declaring a variable as volatile (be it static or not) states that the variable will be accessed frequently by multiple threads. In Java, this boils down to instructing threads that they can not cache the variable's value, but will have to write back immediately after mutating so that other threads see the change. (Threads in Java are free to cache variables by default).

提交回复
热议问题