The volatile keyword can only be used to modify variables, not methods. And volatile guarantees visibility, but not atomicity of operations.
In programming terms, volatile only ensures thread-safe assignment of references to primitive types and common objects.
How volatile works
Why does volatile guarantee visibility but not atomicity? It has to do with how it works.
-
The thread writes the volaitle variable as follows:
-
Change the value of a volatile copy in the thread working memory
-
Flushes the value of the changed copy from working memory to main memory
-
-
The thread reads volatile variables as follows:
-
Reads the latest value of a volatile variable from main memory into the thread’s working memory
-
Reads a copy of the volatile variable from working memory
-
Since there are no lock-related operations involved in the entire process, atomicity cannot be guaranteed, but since the variable value in main memory is flushed in real time, the latest value of the variable can always be seen by different threads at any time, ensuring visibility.
Volatile usage Scenarios
To safely use volatile variables in multiple threads, both must:
-
Setting a variable does not depend on its current value
- For example, number++ and count = count + 5
- For example, Boolean variables
-
This variable is not included in the inequality with other variables
- For example, low < UP when the value remains unchanged
In practical projects, volatile is not used as widely as synchronized because the conditions for its use are not satisfactory in many cases.
Scan the QR code to follow the public account “Ape Must Pass”
Answer the “interview questions” and collect them yourself.
Wechat group for discussion, please add wechat account: zyhui98, note: interview questions add group
This article is published by YBG. Unauthorized reprint is prohibited. Violators are subject to legal liability