简体   繁体   中英

Why is volatile necessary in Java

In Java, all threads uses the same heap. If a thread is caching the operations to the heap, when exactly will it flush to heap?

I have read so many posts but not able to find the answers.

Thanks.

volatile tells Java that the variable may change in multiple threads, and so not to cache the variable. Caching is a processor level construct, and so the processor may flush the cache whenever it wants.

Giving other example: There are websites like Stock websites which want to show the users the most recent data and not some stale data. Right?

So what they do is that they disable caching of webpages so that the pages will not be cached anywhere and all will get the most recent data updated.

Similar is the case with volatile , cores or processors have their own caches and they cache the result thinking that the thread running on current processor does not change the value of a variable then why should it go and read from memory again and again. So it caches it and returns the cached value ( This is for hardware level performance ).

So if like the website example you want to stop other processors using stale values you need to stop caching and volatile is the way to do that in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM