Does Java volatile prevent caching or enforce write-through caching?

后端 未结 2 1090
暖寄归人
暖寄归人 2021-02-05 15:17

I\'m trying to understand Java\'s volatile keyword with respect to writing to a volatile atomic variable in a multithreaded program with CPU caches

2条回答
  •  甜味超标
    2021-02-05 15:21

    The guarantees are only what you see in the language specification. In theory, writing a volatile variable might force a cache flush to main memory, or it might not, perhaps with a subsequent read forcing the cache flush or somehow causing transfer of the data between caches without a cache flush. This vagueness is deliberate, as it permits potential future optimizations that might not be possible if the mechanics of volatile variables were spelled out in more detail.

    In practice, with current hardware, it probably means that, absent a coherent cache, writing a volatile variable forces a cache flush to main memory. With a coherent cache, of course, such a flush isn't needed.

提交回复
热议问题