Tuesday, February 22, 2022

Volatile keyword in java

 Volatile keyword in java used to inform JVM and Thread to read the value of the variable from main method, not from thread stack. Volatile keyword cannot used for method or class declaration. Its only for variable declaration. 

We cannot declare the local variable as volatile, we will get compilation error. "Modifier 'volatile' not allowed here".

Do you think why cannot we declare volatile as local variable?.. 

Yes because all the local variable are line with in a thread stack and it cannot be shared outside the thread, but volatile can be shared across the thread.

When do we choose the volatile?. 

When a need arise the variable value remain same across the application. Better you can use the volatile variables for long and double variables, because they are the 64bit data type, usually it will split like 32+32bit while reading, so when one thread write first 32bit there is a possibility to read the two different thread, so if we make the variable to volatile the changes will be informed the other thread, JVM will take care it.

While reading it do you remember the static keyword also doing the same?? Only one copy will be passed over all the thread??

Static variable can be cached by thread, but volatile cannot be cached by thread. If we use static variable there is a chance, if multiple thread is accessing and updating the value one thread may have cached value, in volatile there is no cache allowed all the thread will be read from main memory.

So now you are clear with volatile and static keyword. 

Do you think about transient ?

transient keyword restrict from serialization, exclude the variable when serializing instance of a class. On deserialzing process default value will be assigned to the variable. (Object null, primitive 0 or false).We will use transient keyword when we convert the domain object in to entity. In domain class we can have n number of variables but in entity class we can have variable for particular Table column, so rest of the domain object not required for while converting from domain to entity, so we can use transient in this case.





No comments:

Post a Comment