The transient and volatile keywords are used for Object serialization and thread synchronization, which are high-level topics in Java.
Transient
Transient is a type modifier and can only be used to modify fields. During Object serialization, variables marked as transient are not serialized.
Example:
Class test {
Transient int A; // not persistent
Int B; // persistence
}
When the Instance Object of the test class is serialized (for example, the Instance Object t of the test class is written to the t.txt file of the hard disk), the content of variable A is not saved, and the content of variable B is saved.
Refer:
The process of converting an object's representation into a byte stream is called serialization (serialization ), rebuilding an object from a byte stream is called deserialization (also called deserialization and deserialization ). Transient provides a language-level labeled data method for data that should not be serialized.
Volatile
Volatile is also a variable modifier and can only be used to modify variables. Each time a member variable modified by volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time.
Here we will explain the Java memory mechanism:
Java uses a primary memory to save the current value of the variable, and each thread has its own working memory. When a thread accesses a variable, it copies the value of the variable to its working memory. In this way, after the thread operates on the variable in its working memory, the copy value of variables in the working memory is different from that in the main memory.
In the Java language specification, it is pointed out that in order to get the best speed, the thread is allowed to save the private copy of shared member variables, and the original value of shared member variables is compared only when the thread enters or leaves the synchronized code block.
In this way, when multiple threads interact with an object at the same time, you must notice that the thread needs to get the shared member variable changes in a timely manner.
The volatile keyword prompts VM: For this member variable, it cannot store its private copy, but should directly interact with the shared member variable.
Suggestion: use volatile on the member variables accessed by two or more threads. You do not need to use this variable when it is already in the synchronized code block or a constant.
Because volatile is used to block the necessary code optimization in the VM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.