March 06, 2010

Difference between Transient and Volatile ?

Transient State of an object can be saved (write to any file) if the class
implements java.io.Serializable interface. In this case all of the field's value
will be saved. If we want any of the field's state must not be saved then we
have to modify that field by transient modifier. For example:


public class SerialDemo implements
java.io.Serializable

{

String name;

double salary;

transient int dob;

}


When we serialize the object of this class then name and salary field's value
will be saved but the value of dob will not be saved.


Volatile:  In a multithreaded program sometimes two or more threads share
same variable. For efficiency each thread keeps its own private copy of the
shared variable and work on it. If you want to restrict the thread from
using own private copy of the variable and let them use master copy of the
shared variable then modify variable using volatile modifier. In
short we can say that volatile modifier can not be cached by the threads.

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts