user1874209
user1874209

Reputation: 11

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.

Upvotes: 1

Views: 388

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 41965

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.

Upvotes: 0

David Pfeffer
David Pfeffer

Reputation: 39852

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.

Upvotes: 1

Related Questions