Difference between volatile and transient in java

JavaObject Oriented ProgrammingProgramming

A volatile keyword is used in a multithreading environment where two threads reading and writing the same variable simultaneously. The volatile keyword flushes the changes directly to the main memory instead of the CPU cache. 

On the other hand, the transient keyword is used during serialization. Fields that are marked as transient can not be part of the serialization and deserialization. We don't want to save the value of any variable then we use transient keyword with that variable. 

Sr. No.KeyVolatileTransient
1
Basic 
Volatile keyword is used to flush changes directly to the main memory
The transient keyword is used to exclude variable during serialization 
2.
Default value 
Volatile are not initialized with a default value.
During deserialization, transient  variables are initialized with a default value 
3
Static 
Volatile can be used with a static variable.
Transient can not be used with the static keyword
4
Final 
Volatile can be used with the final keyword
Transient can not be used with the final keyword

Example of Transient

// A sample class that uses transient keyword to
// skip their serialization.
class TransientExample implements Serializable {
   transient int age;
   // serialize other fields
   private String name;
   private String address;
   // other code
}

Example of Volatile

class VolatileExmaple extends Thread{
   boolean volatile isRunning = true;
   public void run() {
      long count=0;
      while (isRunning) {
         count++;
      }
      System.out.println("Thread terminated." + count);
   }
   public static void main(String[] args) throws InterruptedException {
      VolatileExmaple t = new VolatileExmaple();
      t.start();
      Thread.sleep(2000);
      t.isRunning = false;
      t.join();
      System.out.println("isRunning set to " + t.isRunning);
   }
}
raja
Published on 18-Nov-2019 07:23:31
Advertisements