It indicates that these variables can be modified asynchronously.
In Java, the volatile
keyword is used to indicate that a variable’s value may be changed by multiple threads simultaneously. It ensures that any thread that reads the variable sees the most recent modification made by any other thread. When a variable is declared as volatile
, it prevents the compiler and the runtime environment from reordering code to optimize performance, and it also ensures that changes to the variable are immediately visible to other threads.
Key points about volatile
variables in Java:
- Visibility: Changes to a
volatile
variable are immediately visible to other threads. - Atomicity: The individual read and write operations on a
volatile
variable are atomic. However, compound actions like check-then-act are not atomic and may require additional synchronization. - No Caching: The value of a
volatile
variable is not cached by individual threads. Instead, each thread reads and writes directly from and to the main memory. - Use Cases:
volatile
is typically used in scenarios where a variable is shared among multiple threads, and the developer wants to ensure that changes made by one thread are immediately visible to others. It is not a substitute for proper synchronization mechanisms in more complex scenarios.
Here’s an example of using the volatile
keyword:
public class SharedResource {
private volatile boolean flag = false;
public void setFlagTrue() {flag = true;
}
public boolean isFlag() {
return flag;
}
}
In this example, the flag
variable is declared as volatile
to ensure that changes made by one thread to the flag
variable are immediately visible to other threads.
Keep in mind that while volatile
provides some level of thread safety for simple use cases, for more complex operations and compound actions, you may need to use additional synchronization mechanisms such as synchronized
blocks or Locks
.