Volatile Keyword and Transient Keyword in Java

Volatile Keyword in Java

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.


class Test 


static int var=5; 


In the above example, assume that two threads are working on the same class. Both threads run on different processors where each thread has its local copy of var. If any thread modifies its value, the change will not reflect in the original one in the main memory. It leads to data inconsistency because the other thread is not aware of the modified value.

class Test 


static volatile int var =5; 


In the above example, static variables are class members that are shared among all objects. There is only one copy in the main memory. The value of a volatile variable will never be stored in the cache. All read and write will be done from and to the main memory.

Java Transient Keyword

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

No comments:

Post a comment

All about journals and research paper | What is impact factor? | how the impact factor is calculated? | who calculate the impact factor? Scopous journals

Figure 1: One of my Research Papers When the Scholars are in their Master or PhD or in any research field. They are supposed to writ...