Search code examples
javamultithreadingcachingvolatile

volatile in single core cpu java


(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?


Solution

  • 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.