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

How many types of threads are there in java?

499


What is the old name of java?

499


What state does a thread enter when it terminates its processing in java programming?

572


What is the difference between static (class) method and instance method?

566


What is e java?

553






What is classname class in java?

528


What is the purpose of static methods and variables?

527


Explain the difference between map and flatmap stream operation?

812


What is the public method modifier?

537


how can you take care of mutual exclusion using java threads? : Java thread

605


What is meant by data hiding/encapsulation?

567


How to display all the prime numbers between 1 and n (n is the number, get the input from user)

506


What should I import for arraylist in java?

504


How to perform bubble sort in java?

584


Is there any difference between synchronized methods and synchronized statements?

572