Search code examples
javamultithreadingsynchronizationthread-safety

Confused about synchronization and thread safety in Java


Actually, I am a bit confused in regards of several explanation from website or blog about synchronization and thread-safe. I've done some research on different class of Core Java Api or Java Framework (Collections). And I've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code.

But I need some precision:

  • A class is synchronize so its thread-safe?
  • Or synchronize and thread-safe have two different meaning?

Solution

  • A class is synchronize so its thread-safe ?

    A class is not synchronized. Rather a method, or a block of code is synchronized.

    Synchronization (using synchronized) is one way to make code thread-safe. There are other ways.

    Or synchronize and thread-safe have two different meaning ?

    Yes. They have different meanings.


    And i've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code.

    Actually, if you "noticed" that, you were not paying attention!

    With a synchronized method, only one thread can access the code while holding a given lock; i.e. you get mutual exclusion. If two threads use different locks, then you won't get mutual exclusion.

    The other thing to note is that merely using synchronized does not guarantee thread-safety. You need to use it in the right way:

    • threads need to synchronize on the appropriate objects / locks
    • threads need to synchronize in all appropriate code
    • if the code entails acquiring multiple locks, the locks need to be acquired in an order that avoids deadlocks.