Using volatile keyword with mutable object

前端 未结 5 1240
野的像风
野的像风 2020-12-05 06:47

In Java, I understand that volatile keyword provides visibility to variables. The question is, if a variable is a reference to a mutable object, does vola

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 07:16

    volatile only provides guarantees about the reference to the Object that is declared so. The members of that instance don't get synchronized.

    According to the Wikipedia, you have:

    • (In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.)
    • (In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.

    So basically what you have is that by declaring the field volatile, interacting with it creates a "point of synchronization", after which any change will be visible in other threads. But after that, using get() or set() is unsynched. The Java Spec has a more thorough explanation.

提交回复
热议问题