• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the difference between synchronized and threadsafe.  RSS feed

 
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does synchronized and thread-safe mean the same thing or there is a difference.

thanks
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread-safety is the goal, synchronizing is a tool to reach that goal.

If a class is thread-safe, that means that other classes can use that class without having to worry about multiple threads accessing it concurrently. Making code blocks synchronized helps achieving that, but there are (more modern) alternatives, such as using Locks, Conditions, Barriers, and Latches.
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

So I think means that if we say something is synchronized (e.g HashTable), so it is necessarily Thread safe but vice versa is not true.E.g if we say Struts 2 actions are thread safe so that does not mean it is synchronized.

 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it doesn't make sense to say a class is synchronized. A class can be thread-safe. A code block can be synchronized by using the synchronized keyword.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. A class whose every method is marked synchronized might not necessarily be thread‑safe. It is possible to call non‑thread‑safe code from a synchronized method.
It is possible that different objects hold the lock. If you simply mark methods synchronized, then all instance methods implicitly use this to hold the lock and static methods use the Class<?> object the class is derived from. What if you have an instance method which alters a static field? You may have simultaneous access from a static method and an instance method because they use different objects to hold their locks.

You can implement thread‑safety by putting a Lock on each method, in which case no synchronisation is necessary.

You can also call a class thread‑safe and be mistaken.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!