Difference between volatile and transient keywords in Java

Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. 

Before getting into the differences, let us first understand what each of them actually means.

Volatile:

The Volatile keyword is used to mark the JVM and thread to read its value from primary memory and not utilize cached value present in the thread stack. It is used in concurrent programming in java.

filter_none

edit
close

play_arrow

link
brightness_4
code

class GFG extends Thread {
  
    // using volatile
    volatile boolean working = true;
  
    // if non-volatile it will
    // sleep in main and
    // runtime error will coocur
    public void run()
    {
        long count = 0;
        while (working) {
            count++;
        }
  
        System.out.println("Thread terminated."
                           + count);
    }
  
    // Driver code
    public static void main(String[] args)
        throws InterruptedException
    {
        GFG test = new GFG();
        test.start();
        Thread.sleep(100);
        System.out.println("After Sleeping in Main");
        test.working = false;
        test.join();
        System.out.println("Working set to "
                           + test.working);
    }
}
chevron_right

Output:  



Volatile Code Output

Transient:

The Transient keyword is used with the instance variable to eliminate it from the serialization process. During serialization, the value of the transient field or variable is not saved.

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
  
class Test implements Serializable {
  
    // Making Accesskey transient for security
    transient String accessKey;
  
    // Making age transient as age can be
    // calculated from Date of Birth
    // and current date.
    transient int age;
  
    // serialize other fields
    String name, address;
    public Test(String accessKey, int age,
                String name, String address)
    {
        this.accessKey = accessKey;
        this.age = age;
        this.name = name;
        this.address = address;
    }
}
  
public class GFG {
    public static void main(String[] args)
        throws Exception
    {
        ObjectInputStream in
            = new ObjectInputStream(
                (new FileInputStream(
                    "login_details.txt")));
        Test obj = (Test)in.readObject();
  
        /* Transient variable will be shown 
        null due to security reasons.*/
        System.out.println("Accesskey: "
                           + obj.accessKey);
        System.out.println("Age: "
                           + obj.age);
        System.out.println("Name: "
                           + obj.name);
        System.out.println("Address: "
                           + obj.address);
    }
}
chevron_right

Output:

Transient Code Output

The following table describes the differences:

Transient Volatile
The Transient marked variable prevents it from being serialized. The Volatile marked variable follows happen-before relationship on visibility in multithreaded java program which reduces the risk of memory consistency errors.
It gives control and flexibility over to exclude some object methods from serialization process. It prevents JVM from doing re-ordering which could compromise synchronization. 
During deserialization they are initialized with a default value.  They are not initialized with a default value.
It cannot be used with the static keyword as static variable do not belong to individual instance. During serialization, only object’s current state is concerned.  It can be used with the static keyword.
It cannot be used with the final keyword. Although JVM doesn’t complain about it but during deserialization one will face problem of reinitializing a variable.  It can be used with the final keyword.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :