Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile keyword in multicore vs single processor?

I have heard many people saying that volatile keyword makes more sense in multicore processor than single core processor but don't know the reason. I tried to google but did not help in this aspect. Any reason for it?

As per my understanding volatile keyword should have equal importance whether it is multicore vs single processor. Reason is with volatile , its guaranteed that value will be updated in main memory (heap) instead of keeping it in thread local memory(stack) which can be seen by all threads. So whether its multicore or single processor, how does it makes difference?

like image 411
M Sach Avatar asked May 11 '14 13:05

M Sach


2 Answers

The "sense of volatile" has nothing to do with the number of cores. The JVM hides the underlying architecture. Not to mention that volatile is a language keyword, so it should behave the same on every architecture.

You described what volatile does, and it is correct. The architecture of the application that could require the usage of volatile, nothing else.

If you are interested, here is a great post related to volatile, and the basic concepts of the memory model used in Java.

http://jeremymanson.blogspot.hu/2008/11/what-volatile-means-in-java.html

like image 177
kupsef Avatar answered Nov 10 '22 10:11

kupsef


First of all, "volatile" tries to reduce visibility problems that might occur across different threads (think of the local variables/copies of the shared variables in each thread scope). However, the level of parallelisation is more and easier to visualise when you have multiple CPU cores (caches, registers). IMO, that's why it makes more sense in multi-core architectures. Nevertheless, that visibility issue may even arise when you have a single-core, multiple threads and two of them happens to read the same variable value one after another before the other updates it. In either case, volatile's gonna work the same way regardless of having a single or multi core architecture.

The key is understanding your volatile variables on the CPU cache or registers will be written back to main memory with an IMMEDIATE write policy, so any subsequent reads of the same variable reads the latest updated value.

Volatile only increases the chance of having synched threads - but it's not guaranteed. If you've multiple threads updating the shared data volatile might not be enough alone. There're other features that you can take advantage of with the volatile concept. Please take a look here.

like image 3
stdout Avatar answered Nov 10 '22 10:11

stdout