Java Transient and Volatile Keywords

Transient Keyword:

Transient Keyword marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be ‘serialized’. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

In One word transient keyword is used in serialization process to prevent any variable from being serialized.

Transient keyword provides some control over serialization process and gives flexibility to exclude some of object properties from serialization process.

What kind of variables we can mark as transient?

For example if we have a field called “speed” whose value can be derived from other fields e.g. distance, time then there is no need to serialize it.
we can declare a variable static and transient at same time and java compiler doesn’t complain, but doing that doesn’t make any sense, because transient is to instruct “do not save this field” and static variables are implicitly not saved during serialization.
In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of re-initializing a final variable during deserialization.

Volatile Keyword:

Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory.

Java volatile keyword cannot be used with method or class and it can only be used with variable.
So apart from synchronized keyword in java, volatile keyword is also used to communicate content of memory between threads.
volatile keyword in java guarantees that value of volatile variable will always be read from main memory and “happens-before” relationship in Java Memory model will ensure that content of memory will be communicated to different threads.

When to Use:

  1. we can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. we can avoid this issue by making long and double variable volatile in Java.
  2. Volatile variable can be used as an alternative way of achieving synchronization in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values.
  3. volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory.
  4. Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java:

  1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
  2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread’s local cache.
  3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
  4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
  5. From Java 5, changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.
  6. Reads and writes are atomic for reference variables / most primitive variables (all types except long and double) even without use of volatile keyword in Java.
  7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait.
  8. Java volatile variable object reference can be null.
  9. Java volatile keyword doesn’t means atomic, its common understanding that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
  10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.

Difference between synchronized and volatile keyword in Java:

Volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

  1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods.
  2. Synchronized obtains and releases lock on monitor’s, java volatile keyword doesn’t require that.
  3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java.
  4. Synchronized method affects performance more than volatile keyword in Java.
  5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and “main” memory. While synchronized synchronizes the value of all variable between thread memory and “main” memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.
  6. We can not synchronize on null object but your volatile variable in java could be null.
  7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire.

    In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is handy and can save performance overhead which comes with use of synchronization in Java.
image logo

No comments :

Post a Comment