Java volatile Modifier
Suppressing Field Value Caching with the volatile Modifier
In a multithreaded environment, each thread may cache field values individually to improve performance. This improves performance by reducing the process of reading from and writing to original memory.
However, this can also be used to protect against the risk that different threads may see different reference values for the same field. If you want to avoid value inconsistencies, you can add the volatile modifier to restrict caching of the field value.
public class ModVolatile {
volatile int shareValue; // Excluded from caching
}
It is also possible to express the place where the corresponding field is manipulated with a synchronized block or modifier. Field values handled inside a synchronized block are always read from and written back to original memory, so cache inconsistencies can be avoided. However, wrapping simple read and write operations in a synchronized block is excessive, so the volatile modifier is used when such operations occur frequently.