English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The difference between volatile and transient in Java

The volatile keyword is used in a multi-threaded environment where two threads read and write the same variable at the same time. The volatile keyword refreshes changes directly to main memory, not to CPU cache. 

On the other hand, the transient keyword is used in the serialization process. Fields marked as transient cannot be part of serialization and deserialization. We do not want to save any variable values, so we use the transient keyword with the variable. 

IndexKeyVolatileTemporary
1
Basic 
The volatile keyword is used to refresh changes directly to main memory
Transient keywords are used to exclude variables during serialization 
2.
Default value 
Volatile does not use default values to initialize.
During deserialization, transient variables will be initialized with default values 
3
Static 
Volatile can be used with static variables.
Cannot be used with the static keyword temporarily
4
Finally 
Can be used with the final keyword together
Transient cannot be used with the final keyword together

Transient example

// A sample class that uses the transient keyword to
//Skip its serialization.
class TransientExample implements Serializable {
   transient int age;
   //Serialize other fields
   private String name;
   private String address;
   //Other code
}

Example of volatility

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);
   }
}