Henry Wong wrote:To further elaborate this, the volatile variable is used as the basis for the atomic classes...
Brendon McCullum wrote:@Henry, it's getting a bit confusing as I study it more. As I see this, volatile serves a useful purpose, only when the operations to the underlying variable are atomic. I referred to your reply on this thread : Javaranch. As you say here, that the assignment operation is also not atomic and the reader thread could read in the value before the writer thread. If that's the case, I guess none of the operations are atomic, and volatile won't serve any purpose. The only use that I understand is when there's a happens-before relationship in the access order of variables. If that's the case, it becomes kind of a sequential order, where a thread first updates a variable, writes the changes to main memory instead of cache, and then subsequently other threads read it.
Brendon McCullum wrote:
Also, I'd be grateful if you could explain a bit about optimistic locking as you've mentioned in your post. I googled this, but found that it's related to Hibernate, J2EE rather than the core Java part on which I'm stressing. Thanks a lot.
Brendon McCullum wrote:
Basically, here a new value is being assigned to count. But that's an assignment operation, right? If it's not, can you list out any use case where volatile is guaranteed to succeed, in other way anything that is inherently atomic without explicit synchronization.
Brendon McCullum wrote:
Here, if I make the count variable as volatile, no extra synchronization or locks would be needed, right? I've removed the compare so it remains a single atomic operation now. What I understand that volatile is guaranteed to work in atomic operations (both for reads and writes), and in other cases, we can either use conventional synchronization (pessimistic locking), or maybe go for some other CAS implementing algorithms (as the Atomic classes in Java do, and the one you shared above). Please correct me in case I'm getting this wrong. Also, I appreciate your efforts for answering my queries. Thanks.