What is the difference between volatile and synchronized?

Both volatile and synchronized can be used to achieve synchronization in multi-threading, but they have different purposes and usage patterns.

  1. The volatile keyword is used to ensure visibility: when a variable is declared as volatile, a thread will immediately write the modified value back to the main memory when modifying the variable, and the thread will first read the latest value from the main memory when reading the variable. Therefore, for a variable shared by multiple threads, if you want any modification by one thread to be visible to other threads, you can use the volatile keyword. However, volatile does not guarantee atomicity, which means that for compound operations (such as incrementing ++), volatile cannot guarantee the atomicity of operations.
  2. The synchronized keyword is used to ensure atomicity and mutual exclusion: when a method or code block is declared as synchronized, only one thread can execute that method or code block at a time, while other threads need to wait. This keyword guarantees the atomicity and mutual exclusion of threads, meaning that when a thread is executing synchronized code, other threads cannot access that code block, thus preventing data inconsistency issues caused by concurrent access in multithreading. The use of the synchronized keyword requires consideration of object locking, typically achieved through object locks or class locks to synchronize code blocks or methods.

Therefore, the volatile keyword is suitable for scenarios that require high visibility of variables, while the synchronized keyword is suitable for scenarios that require high atomicity and mutual exclusion.

广告
Closing in 10 seconds
bannerAds