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
How many ways can you break a singleton class in java?
Which java version is latest?
What language is java written?
What are the principle concepts of oops?
State the significance of public, private, protected class?
What is variable in java?
How do you compare values in java?
What is the difference between state-based unit testing and interaction-based unit testing?
Is there any tag in htm to upload and download files?
what is daemon thread and which method is used to create the daemon thread? : Java thread
What do you mean by stack?
What is singletonlist in java?
What are variable arguments or varargs?
What is object-oriented paradigm?
Give a brief description of java socket programming?