Search code examples
javaandroiddatabaseandroid-roomvolatile

Does volatile in java allow for instances to be deleted?


I am watching a video tutorial on Room db. In the video, the instructor says:

"Volatile just means that the instance will be able to get rid of itself or remove itself if need be."

However, based on my understanding, volatile means that the variable will be stored in the main memory rather than taken from the cache.

This post confirmed that as well: http://tutorials.jenkov.com/java-concurrency/volatile.html

How does volatile allow for an instance to remove itself?

Thanks!


Solution

  • The CPU caches are always coherent; it is the source of truth; so memory could be completely out of sync.. indefinitely.. perfectly fine. A write of a volatile variable doesn't trigger the whole cache to be flushed to main memory; that would be extremely inefficient. Even a single cache line isn't force to flush to main memory.

    What typically is meant (on X86) with 'flushing' to main memory is that when a volatile store is done, the CPU waits for the stores in the store buffer to be committed to the cache before allowing any loads to execute. This prevents the reordering of an older store with a newer load to a different address.

    The "remove itself" stuff makes no sense at all.

    This article is incorrect.

    http://tutorials.jenkov.com/java-concurrency/volatile.html

    This is not how it works. Caches are synchronized using a cache coherence protocol like MESI. So a write to a cacheline on one CPU will always lead to the copies of the cacheline in the other CPU to be invalidated.

    Warning: when dealing with the JMM it is best to keep it fully abstract and not reason about implementation concerns like cache invalidation etc. It is fun.. but you can shoot yourself very easily in the foot.