简体   繁体   中英

Confused about synchronization and thread safe ? 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 ?

Best regards

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; ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM