volatile
Keyword in Java
The volatile
keyword ensures visibility and consistency of variables in a multithreaded environment.
Key Points:
- Visibility: Changes to a
volatile
variable by one thread are immediately visible to others. - No Caching: Prevents threads from caching the variable locally; always reads from main memory.
- Usage: Ideal for flags or variables shared between threads, but not suitable for complex synchronization.
Example:
java
private volatile boolean running = true;
Use volatile
for lightweight thread communication. For atomicity, consider synchronized
or java.util.concurrent
classes.