Java ‘volatile’ Keyword Guide
volatile是Java中的关键字,用于修饰变量。它具有两个主要的作用:
- Ensure visibility of variables: When a variable is marked as volatile, threads will directly read its value from the main memory instead of their own cache. This ensures that any modifications made to the variable by all threads are visible, preventing errors caused by inconsistent data between threads.
- Prohibit instruction reordering: In a multi-threaded environment, compilers and processors may reorder instructions to improve program efficiency. However, some instruction reordering may cause the program’s results to be incorrect. By using the volatile keyword to modify variables, compilers and processors can be prevented from reordering instructions for that variable, thus ensuring program correctness.
It’s important to note that volatile can only guarantee visibility and prevent instruction reordering, but it cannot guarantee atomicity. If atomicity is needed, synchronized keyword or other methods like Lock can be used to achieve it.
In conclusion, the main purpose of the volatile keyword is to ensure the visibility of variables to all threads and prevent instruction reordering. In a multi-threaded environment, if there are shared variables and the read/write operations on the variables do not depend on the current value, consider using the volatile keyword to decorate the variable.