Declaring an object as volatile

后端 未结 4 1279
有刺的猬
有刺的猬 2021-02-05 15:33

If you declare a member variable as volatile in Java, does this mean that all the object\'s data is stored in volatile memory, or that the reference to the object is stored in v

4条回答
  •  猫巷女王i
    2021-02-05 15:59

    If you declare a member variable as volatile in Java, does this mean that all the object's data is stored in volatile memory, or that the reference to the object is stored in volatile memory?

    When we declare the object as volatile we are actually telling the underlying processor how to work with the Volatile Object.Every time it is read by CPU instruction a fresh copy is called from Heap and every time a write is done on the object it is saved to heap and is available to other threads. Thus ,the processor does not picks from cache old value neither it write to cache and waits for cache to be written back to the Heap.

    Does it make obj.c and obj.i thread safe or not? No. It just gurantees that you will always have a fresh copy when you will read the object.And it is very well possible that while you using the variable and processing logic based on varilable value someone might have changed the value in background and when you updated it ,you are updating a different value.

提交回复
热议问题