The principle volatile keyword
1, the semantic analysis of the volatile keyword
Role: let other threads can immediately perceive a thread of a multi-variable changes
- Ensure the visibility of
changes to shared variables, other threads can immediately perceive - Ensure orderly
guarantee volatile modified the code in the same position when reordering The principle
will be taken from the main memory directly For that volatile variables will compile time using the Lock command, other threads to use Lock command modified variables2, volatile usage scenarios
- Status flag (switching mode)
a thread by changing the value of the shared variable, to control the other end of the real - Double-checked locking (double-checked-locking) DCL
lazy single embodiment Need to use sequential
3, the difference between volatile and synchronized
- Using a
volatile variable modifications, synchronized statement blocks and modification methods - Atomicity guarantees
synchronized to ensure the atomicity, volatile can not be guaranteed atomicity - Visibility assurance
can be guaranteed, but the principle of different
volatile variables plus lock, synchronized using monitorEnter and monitorExit - Guarantee orderliness
volatile prohibited reordering, the ordering guarantees
sychronized by adding heavyweight lock will degenerate into a serial parallel, easily causing obstruction