From Javadocs
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
When changes made to a volatile variable are always visible to any other thread, then why volatile variable cant be used in case of multiple threads writing to that variable. Why is volatile only used for cases when one thread is writing or reading to that while the other thread is only reading the variable?
If changes are always visible to other threads, then suppose if thread B wants to write to that variable, it will see the new value(updated by thread A) and update it. And when the thread A again wants to write, it will again see the updated value by thread B and write to it.Where is the problem in that?
In short, i am not able to understand this.
if two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use synchronization in that case to guarantee that the reading and writing of the variable is atomic.