2

(In case of single CPU ) for understanding volatile -I know volatile forces thread to use main memory and will not keep copy in its local memory.

In one of the StackOverFlow post I see that java threads uses CPU cache and using volatile it will force to use main memory

Thread Caching and Java Memory model.

If this is the case then there should not be issue with memory visibility, since one thread can see values written by other thread (assuming on single CORE CPU we will have single cache). so volatile is usefule for single CPU?

Rehan Javed
  • 418
  • 3
  • 14
JavaKaKida
  • 23
  • 2

1 Answers1

6

First, volatile does not force threads to use main memory. It forces threads to behave as if they were forced to use main memory. This is important because actually using main memory would slow things down to a crawl on a modern system. Fortunately that definitely doesn't actually happen.

Second, it doesn't matter how many actual cores the CPU has. A single core CPU can perfectly emulate a dual core CPU, and a JVM implementation is free to do that if it wants to. The requirement to do some form of synchronization is a Java language requirement and is independent of the hardware -- one of the whole points of Java is that you don't have to worry about that.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • is my memory visualization is correct?where CPUs cache will be use by thread to caching values ? – JavaKaKida Nov 17 '17 at 09:29
  • @sachinyewale I'm not sure I understand exactly what you're asking. But yes, the CPU's caches will be used for threads to communicate. (In fact, accelerating this process is one of the primary purposes of the L3 cache on modern Intel CPUs.) – David Schwartz Nov 17 '17 at 09:31
  • if same CPU cache will be used by threads then , conceptually if one thread write some variable in given cache , then subsequently other thread can read that value without valatile , since it is same cache , correct if my if I am wrong. – JavaKaKida Nov 17 '17 at 11:37
  • @sachinyewale Sure, that can happen. Sometimes you can break the rules and it still happens to work ... until the time it doesn't. – David Schwartz Nov 18 '17 at 02:19
  • if multiple thread can use same cache then do we require volatile (for resolving caching issue in single core machine)? I know we should, but just wanted to understand underlying reason – JavaKaKida Nov 19 '17 at 06:09
  • Who knows? CPUs can do whatever they want. – David Schwartz Nov 19 '17 at 21:22