What is Transient and volatile

Answer Posted / jagan kumar(zylog systems ltd.

Transient
.........
Only variable can be declared as Transient, When
used as a Modifier in a variable Declaration it suggests
that a variable may not be return out when the class is
serialized

Volatile
.........
The keyword volatile can be used to declare
variables. The use of the keyword volatile in a variable
declaration suggests the compiler that multiple threads may
access the variable. Therefore the value of the variable
may change unexpectedly. A Compile time error will occur
declaring a variable both volatile and final.

Example for Volatile:
.....................

volatile int v = 0;
Thread 1:
v++;
Thread 2:
v--;

The questioners usually want the answer "v can only
be 0 after this code is run", because

volatile int v = 0;
Thread 1:
r1 = v;
r2 = r1 + 1;
v = r2;
Thread 2:
r3 = v;
r4 = r3 - 1;
v = r4;
So, if Threads 1 and 2 both read v and see the value
0, then Thread 1 will write 1 to it and Thread 2 will
write -1 to it. You are not guaranteed to see the value 0!

Is This Answer Correct ?    16 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Which method cannot be overridden in java?

615


What are invisible components?.

1686


how to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state? Or extending thread class or implementing runnable interface. Which is better? : Java thread

602


How do you check if a number is a perfect square?

522


How static variable work in java?

612






What is a classloader in java?

540


What is a singleton class in Java?

520


What is the difference between class & object?

565


What is struts in java?

590


Explain the difference between protected and default access.

529


If goto and const is reserve words than why it is not work in java?

1513


Is java type safe?

515


What is set string?

607


What is t type java?

632


Can inner class extend any class?

610