What is Transient and volatile

Answer Posted / manodeep pandey

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. 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 ?    5 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

what is difference between equals and ==?

592


How can we use primitive data types as objects?

562


how can you catch multiple exceptions in java?

543


what is heap memory?

660


What are jee technologies?

538






Why runnable interface is used in java?

578


What will happen to the exception object after exception handling?

582


What Is Composition?

587


Can we make main() thread as daemon?

580


String and stringbuffer both represent string objects. Can we compare string and stringbuffer in java?

558


What is an interface in java? Explain

580


Which class represents the socket that both the client and server use to communicate with each other?

578


What is a qualifier in a sentence?

533


explain autoboxing in java?

597


What is methods in java?

516