Reputation: 1
In Java, the volatile
keyword is for direct read and write from main memory so that reads or writes won't be lost if multiple threads are accessing a variable.
Without using volatile
, is there any other way to achieve this functionality? I came across this question but couldn't figure out a solution.
Upvotes: 0
Views: 154
Reputation: 269637
The Java Language Specification describes a set of happens-before relationships, and a set of synchronizes-with actions. If one action synchronizes-with a following action, it happens-before. A write is guaranteed to be visible if happens-before a read, in this technical sense.
Writes performed inside a synchronized
block are visible to threads that synchronize on that lock afterwards, because release of a lock synchronizes-with acquisition by another thread.
A write to a volatile
variable synchronizes-with subsequent reads of that variable, so it is visible.
A number of the utilities in the java.util.concurrent
also provide a happens-before relationship. For example, actions taken by a thread before it calls countDown()
on a CountDownLatch
are visible to threads that return from a call to await()
on that latch. Of course, many of these APIs achieve this by using volatile
, synchronized
themselves.
Upvotes: 1
Reputation: 7956
Basically, if you want to safely access a non-volatile variable from multiple threads, you need to surround all read/write access to the variable with synchronized
blocks that use a shared monitor. Read access to volatile
variables (in general) need not be synchronized, because each read operation is guaranteed to see the last write to the variable by any thread.
It is important to notice that using volatile
fields alone does not eliminate the need for synchronization when you e.g. need to atomically read a value of a variable, followed by a write to the same variable. A common use case for this is incrementing a counter. As @Louis Wasserman suggests, for these purposes, classes in the java.util.concurrent.atomic
package provide reliable and easy to use methods, such as compareAndSet(...)
and incrementAndGet()
.
Upvotes: 1