Transient and Volatile.

What is the difference between Transient and Volatile. Does volatile variable is serialized and synchronised.

Questions by sha_kr2001   answers by sha_kr2001

Showing Answers 1 - 21 of 21 Answers

transient and volatile both are used to define non -serializable members of any class.means if we want to convert an object into byte stream and write into file we serialize the class but if any variable or method which we dont want to serialize,we can specify them by above.note---VOLATILE is used with variable andTRANSIENT is  used with methods. 

  Was this answer useful?  Yes

Volatile is assigned with variable when we synchronze that variable in multi threading environment.It also indicate to have a master copy of it ,that is keep an updated value of this variable.
 Transient we use when we want to serialize and object and that object keeps any thread or socket or any other type of member present in that object,then we have to specify them transient so that JVM does not try to serialize them otherwise error will be thrown.

  Was this answer useful?  Yes

Volatile:
Threads dont cache method copy of  Volatile instance variables. Each time when the var is used the thread gets latest copy.

Transient:
instance var not serialized ever. After deserialization its value is null(object) or zero(primitive type).

Sarje

  • Aug 14th, 2009
 

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.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions