[java] What are Transient and Volatile Modifiers?

Can someone explain what the transient and volatile modifiers mean in Java?

This question is related to java serialization storage modifier

The answer is


Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2


volatile and transient keywords

1) transient keyword is used along with instance variables to exclude them from serialization process. If a field is transient its value will not be persisted.

On the other hand, volatile keyword is used to mark a Java variable as "being stored in main memory".

Every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

2) transient keyword cannot be used along with static keyword but volatile can be used along with static.

3) transient variables are initialized with default value during de-serialization and there assignment or restoration of value has to be handled by application code.

For more information, see my blog:
http://javaexplorer03.blogspot.in/2015/07/difference-between-volatile-and.html


Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.


The volatile and transient modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.

The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient-ness. Or they may ignore it.

(Note that the JLS permits a static field to be declared as transient. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)

The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long or double fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.


1 - But not to local variables or parameters.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to serialization

laravel Unable to prepare route ... for serialization. Uses Closure TypeError: Object of type 'bytes' is not JSON serializable Best way to save a trained model in PyTorch? Convert Dictionary to JSON in Swift Java: JSON -> Protobuf & back conversion Understanding passport serialize deserialize How to generate serial version UID in Intellij Parcelable encountered IOException writing serializable object getactivity() Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Examples related to storage

AWS EFS vs EBS vs S3 (differences & when to use?) "Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat How to get my Android device Internal Download Folder path How to Get True Size of MySQL Database? Android saving file to external storage Django CharField vs TextField What column type/length should I use for storing a Bcrypt hashed password in a Database? How to create a file on Android Internal Storage? What are Transient and Volatile Modifiers? Android: Storing username and password?

Examples related to modifier

SwiftUI - How do I change the background color of a View? What is the 'open' keyword in Swift? What are Transient and Volatile Modifiers? What does the "static" modifier after "import" mean?