Home >Java >javaTutorial >Analyze the role and applicable conditions of the volatile keyword in Java
Explore the role and usage scenarios of the volatile keyword in Java
In Java, we often use keywords to control the visibility of variables, thread synchronization and memory Visibility and other issues, and one of the keywords is volatile. The volatile keyword can ensure the visibility and ordering of modified variables. Its function is to prevent instruction reordering and ensure the atomicity of thread operations on variables.
1. The role of volatile keyword
2. Usage scenarios of volatile keyword
The sample code is as follows:
public class VolatileExample { private volatile boolean flag = false; public void setFlag() { flag = true; } public void doSomething() { while (!flag) { // do something } System.out.println("Flag has been set to true"); } public static void main(String[] args) { VolatileExample example = new VolatileExample(); new Thread(() -> example.setFlag()).start(); new Thread(() -> example.doSomething()).start(); } }
When you run the above code, thread B will wait in a loop until thread A sets the flag flag to true before continuing.
The sample code is as follows:
public class Singleton { private volatile static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
In the above code, if the volatile keyword is not used to modify the instance variable, then after thread A executes to synchronized (Singleton.class), the thread B may directly obtain an uninitialized instance through null judgment.
Summary:
The volatile keyword is a thread synchronization mechanism in Java, which is used to ensure the visibility and orderliness of variables while prohibiting reordering of instructions. Main usage scenarios include: status flags and double-checked lock mode. When using the volatile keyword, you need to pay attention to ensure the reasonable use of variables and try to avoid unnecessary synchronization and competition, thereby improving the efficiency and performance of the program.
The above is the detailed content of Analyze the role and applicable conditions of the volatile keyword in Java. For more information, please follow other related articles on the PHP Chinese website!