Introduction
The volatile and transient keywords in Java serve different purposes. The volatile keyword ensures visibility of changes to a variable across multiple threads, preventing caching issues in concurrent programming. The transient keyword is used in serialization to indicate that a variable should not be serialized.

In this article, we will discuss the differences between volatile and transient, their use cases, and how they impact Java applications.
Volatile in Java
The volatile keyword in Java is used to indicate that a variable's value may be changed by multiple threads simultaneously. When a variable is declared as volatile, it ensures that every thread reads the most recent value of the variable directly from the main memory instead of relying on the cached value.
Key Features of Volatile
- Ensures visibility of changes to variables across threads.
- Prevents compiler optimizations that could lead to inconsistent data.
- Does not provide atomicity for compound operations.
- Used for variables that are shared between multiple threads.
Syntax of Volatile
volatile dataType variableName;Example of Volatile in Java
class SharedResource {
volatile boolean flag = false;
}
class VolatileExample extends Thread {
private SharedResource resource;
public VolatileExample(SharedResource resource) {
this.resource = resource;
}
public void run() {
System.out.println("Thread started");
while (!resource.flag) {
// Waiting for flag to change
}
System.out.println("Flag changed, thread exiting");
}
}
public class VolatileDemo {
public static void main(String[] args) throws InterruptedException {
SharedResource resource = new SharedResource();
VolatileExample thread = new VolatileExample(resource);
thread.start();
Thread.sleep(1000); // Simulate delay
System.out.println("Changing flag value");
resource.flag = true;
}
}
Output:
Thread started
Changing flag value
Flag changed, thread exiting
Explanation:
- A SharedResource class contains a volatile boolean flag.
- A separate thread (VolatileExample) continuously checks the flag's value.
- The main thread updates the flag after a delay.
- The change in the flag's value is immediately visible to all threads due to the volatile keyword.
When to Use `volatile` in Java?
The `volatile` keyword is particularly useful in specific scenarios where thread visibility & consistency are critical. Let’s discuss some common situations where you should consider using `volatile`:
1. Multi-threaded Environments with Shared Variables
When multiple threads are accessing & modifying the same variable, `volatile` ensures that all threads see the most recent value of the variable. Without `volatile`, threads might work with stale or cached values, leading to inconsistent behavior.
For example: Imagine a program where one thread updates a configuration setting, & other threads need to react to this change immediately. Using `volatile` ensures that the updated value is visible to all threads without delay.
2. Flags for Thread Control
`volatile` is often used for flags that control the execution of threads. For instance, a `boolean` flag can be used to signal a thread to stop or start its execution. Since the flag is shared between threads, declaring it as `volatile` ensures that changes to the flag are immediately visible.
For example: In a multi-threaded application, you might have a `stop` flag that tells all threads to terminate gracefully. Declaring this flag as `volatile` ensures that all threads see the updated value as soon as it is changed.
public class StopThreadExample {
private volatile boolean stop = false;
public void stopThread() {
stop = true;
}
public void runThread() {
Thread workerThread = new Thread(() -> {
while (!stop) {
// Perform some work
}
System.out.println("Thread stopped.");
});
workerThread.start();
}
public static void main(String[] args) throws InterruptedException {
StopThreadExample example = new StopThreadExample();
example.runThread();
Thread.sleep(2000); // Simulate some delay
example.stopThread(); // Stop the thread
}
}
In this example, the `stop` flag is declared as `volatile`. When the `stopThread()` method sets the flag to `true`, the worker thread immediately sees the change & stops its execution.
3. Avoiding Double-Checked Locking Issues
In some cases, `volatile` is used to fix issues in double-checked locking, a common pattern used to implement lazy initialization in singleton classes. Without `volatile`, the double-checked locking pattern can fail due to thread visibility issues.
4. Performance Considerations
While `volatile` ensures visibility, it does not provide atomicity for compound actions. For example, if you need to perform operations like incrementing a counter (`count++`), `volatile` alone is not sufficient. In such cases, you should use atomic classes like `AtomicInteger` or synchronization.



