The volatile keyword in Java is used to ensure that changes made to a variable by one thread are immediately visible to all other threads. It helps maintain data visibility in a multithreaded environment by forcing reads and writes to occur directly from main memory.
Key Points: • A volatile variable is always read from and written to main memory. • It ensures visibility of changes across multiple threads. • It prevents threads from using cached copies of the variable. • volatile does not provide atomicity for compound operations such as increment (count++). • It is commonly used for status flags, configuration values, and thread control variables.
Example: If one thread updates a stop flag and another thread continuously checks that flag, declaring the flag as volatile ensures that the updated value is immediately visible to all threads.
Code Example:
class SharedResource {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void execute() {
while (running) {
// Task execution
}
System.out.println("Thread stopped");
}
}Interview Tip: A concise interview answer is:
"The volatile keyword ensures that a variable's latest value is always read from main memory, making updates visible to all threads. It provides visibility but does not guarantee thread safety for compound operations, for which synchronization or atomic classes are required."