What are Transient and Volatile Modifiers?

Answer Posted / shashank jain

Java defines two interesting type modifiers: transient and
volatile. These modifiers are
used to handle somewhat specialized situations.
When an instance variable is declared as transient, then its
value need not persist
when an object is stored. For example:
class T {
transient int a; // will not persist

int b; // will persist
}
Here, if an object of type T is written to a persistent
storage area, the contents of a
would not be saved, but the contents of b would.
The volatile modifier tells the compiler that the variable
modified by volatile can
be changed unexpectedly by other parts of your program. One
of these situations
involves multithreaded programs. (You saw an example of this
in Chapter 11.) In a
multithreaded program, sometimes, two or more threads share
the same instance
variable. For efficiency considerations, each thread can
keep its own, private copy of
such a shared variable. The real (or master) copy of the
variable is updated at various
times, such as when a synchronized method is entered. While
this approach works
fine, it may be inefficient at times. In some cases, all
that really matters is that the
master copy of a variable always reflects its current state.
To ensure this, simply specify
the variable as volatile, which tells the compiler that it
must always use the master
copy of a volatile variable (or, at least, always keep any
private copies up to date with
the master copy, and vice versa). Also, accesses to the
master variable must be executed
in the precise order in which they are executed on any
private copy.

Is This Answer Correct ?    14 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How can I debug the Java security exceptions and AccessControlExceptions?

868


can any body body expalin best definitions & best real time exaples for opps concepts.

2015


Explain 5 features introduced in jdk 1.7?

780


Explain about the interpreter in java?

811


Are primitives objects?

752






What is the difference between assignment and initialization?

762


Which java collection does not allow null?

884


How do I know if java is installed?

741


What is an anonymous class in java?

745


Which category the java thread do fall in?

733


What is the file type?

769


How do you check if an arraylist is not empty?

754


we have syntax like for(int var : arrayName) this syntax is to find whether a number is in the array or not.but i want to know how to find that number's location.

1780


Difference between this() and super() ?

746


Can a private method be declared as static?

750