10 Points About Volatile Modifier or Field in Java

If a field is shared between multiple threads and one of them change its value i.e. one thread reads from the field which is written by other threads, then, by using a volatile modifier, you can synchronize access to this field. The volatile modifier in Java provides visibility and ordering guarantee without any locking. You might know that compiler and JVM can re-order your code due to various reasons e.g. performance improvement which can be a problem in concurrent Java application.

By making a filed in Java you can instruct compiler, JVM, and JIT to doesn't reorder them preventing subtle and hard-to-find multi-threading bugs.

Similarly, the visibility guarantee ensures that memory barriers are refreshed when a variable is read, hence all the changes made by one thread before writing into a variable is visible to the other thread who read from a volatile variable, this is also a part of "happens-before" guarantee provided bvariables.

Though, you need to be a little bit careful because doesn't provide atomicity and mutual exclusive access, which is one of the key difference between synchronized and keyword in Java. Hence, the variable should only be used if the assignment is the only operation performed on them.

In this article, I am going to 10 such important points about volatile modifier in a field which will help you to learn this useful concept better in Java multi-threading world. If you want to learn more, you can always read Java concurrency in Practice by Infocampus

10 Points about volatile variable in Java

Here are a couple of useful points a Java developer should know about modifier. Since many of you might not have the first-hand experience of using variable in your application, this points will help you to understand the existing code written by some experienced programmers and which uses the volatile modifier for synchronization and inter-thread communication.