Table of contents
1.
Introduction
2.
Volatile in Java
2.1.
Key Features of Volatile
2.2.
Syntax of Volatile
2.3.
Example of Volatile in Java
2.4.
When to Use `volatile` in Java?
3.
Transient in Java
3.1.
Key Features of Transient
3.2.
Syntax of Transient
3.3.
Example of Transient in Java
4.
Differences Between Volatile and Transient in Java
5.
Frequently Asked Questions
5.1.
When should I use the volatile keyword in Java?
5.2.
What happens if a transient variable is serialized in Java?
5.3.
Can a variable be both volatile and transient?
6.
Conclusion
Last Updated: Sep 19, 2025
Medium

Difference between volatile and transient keywords in Java

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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. 

Difference between volatile and transient keywords in Java

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;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Thread started
Changing flag value
Flag changed, thread exiting


Explanation:

  1. A SharedResource class contains a volatile boolean flag.
     
  2. A separate thread (VolatileExample) continuously checks the flag's value.
     
  3. The main thread updates the flag after a delay.
     
  4. 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.

Transient in Java

The transient keyword is used in Java to indicate that a variable should not be serialized. When an object is serialized, all its variables are saved to a file or a database. However, if a variable is marked as transient, it will not be included in the serialization process.

Key Features of Transient

  • Prevents a variable from being serialized.
     
  • Useful for security-sensitive data such as passwords.
     
  • The variable will have its default value after deserialization.
     
  • Does not affect normal program execution.

Syntax of Transient

class ClassName implements Serializable {
    transient dataType variableName;
}

Example of Transient in Java

import java.io.*;
class User implements Serializable {
    private static final long serialVersionUID = 1L;
    String username;
    transient String password;
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}
public class TransientDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user = new User("JohnDoe", "secret123");
        // Serialization
        FileOutputStream fos = new FileOutputStream("user.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(user);
        oos.close();
        fos.close();
        // Deserialization
        FileInputStream fis = new FileInputStream("user.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        User deserializedUser = (User) ois.readObject();
        ois.close();
        fis.close();
        System.out.println("Username: " + deserializedUser.username);
        System.out.println("Password: " + deserializedUser.password);
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Username: JohnDoe
Password: null


Explanation:

  1. The User class has two fields: username and password.
     
  2. The password field is marked as transient, so it is not saved during serialization.
     
  3. After deserialization, the password field is null while username retains its value.

Differences Between Volatile and Transient in Java

ParametersVolatileTransient
PurposeEnsures variable visibility in multi-threadingPrevents variable from being serialized
ScopeAffects all threads accessing the variableAffects only serialization process
Used ForSynchronization and thread safetySecurity-sensitive data
PersistenceValue is retained across executionsValue is lost after serialization
Example Use CaseFlag variables for inter-thread communicationPasswords, sensitive data

Frequently Asked Questions

When should I use the volatile keyword in Java?

Use volatile when multiple threads need to read and write a shared variable, and you want to ensure that the latest value is always read directly from memory.

What happens if a transient variable is serialized in Java?

A transient variable is ignored during serialization, meaning its value will not be saved and will be reset to its default value upon deserialization.

Can a variable be both volatile and transient?

No, because volatile ensures visibility in multi-threading while transient prevents serialization. These functionalities do not overlap.

Conclusion

In this article, we discussed the difference between volatile and transient keywords in Java. The volatile keyword ensures visibility and consistency of variables across multiple threads, while transient prevents serialization of specific fields in an object. Both transient and volatile in java serve different purposes—volatile for thread safety and transient for controlling object serialization in Java.

Live masterclass