English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The volatile keyword is used in a multi-threaded environment where two threads read and write the same variable at the same time. The volatile keyword refreshes changes directly to main memory, not to the CPU cache.
On the other hand, the transient keyword is used during the serialization process. Fields marked as transient cannot be part of serialization and deserialization. We do not want to save the value of any variable, so we use the transient keyword along with that variable.
Serial number | Key | Volatile | Short-lived |
---|---|---|---|
1 | Basic | The volatile keyword is used to refresh changes directly to main memory | The transient keyword is used to exclude variables during serialization |
2. | Default value | Volatile does not use default values for initialization. | During deserialization, transient variables will be initialized with default values |
3 | Statico | La volatilità può essere utilizzata insieme a variabili statiche. | Non può essere utilizzata insieme alla parola chiave static |
4 | Infine | Può essere utilizzata insieme alla parola chiave final | La transitorietà non può essere utilizzata insieme alla parola chiave final |
//Una classe di esempio che utilizza la parola chiave transient //Salta la serializzazione. class TransientExample implements Serializable { transient int age; //Serializzare altri campi private String name; private String address; //Altre code }
class VolatileExmaple extends Thread{ boolean volatile isRunning = true; public void run() { long count = 0; while (isRunning) { count++; } System.out.println("Thread terminated. " + count); } public static void main(String[] args) throws InterruptedException { VolatileExmaple t = new VolatileExmaple(); t.start(); Thread.sleep(2000); t.isRunning = false; t.join(); System.out.println("isRunning set to " + t.isRunning); } }