Highbridge Capital Interview Question
Java DevelopersTeam: Risk Metrics
Country: United States
Interview Type: Phone Interview
Answers (including the book) that say volatile is related to threading are wrong. They're what most people think (possibly including your interviewer), but they're wrong.
Volatile was created in order to handle memory-mapped I/O. For example, the compiler is not allowed to remove redundant stores to the same address since the redundant stores may have meaning to I/O subsytems.
Volatile is neither necessary nor sufficient to handle values accessed from multiple threads.
It's not necessary because it can produce far more memory accesses than is necessary since the complier is not allowed to do much. Using, for example, pthreads you can get the consistency guarantees you need with far less memory traffic.
It's not sufficient because the standard doesn't require it. The C standard says nothing about threads. Modern CPU architectures have a very complicated memory ordering models in order to eek out performance and those models require the use of memory barrier instructions to guarantee cross-thread visibility semantics. pthreads guarantees memory barriers, volatile doesn't.
volatile is applied on variable which is shared between different threads. this keyword make sure that thread doesn't not cache the value of variable and get most updated value every time.
- Amit July 26, 2012