• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronized and unsynchronized  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable is synchronized while Hashmap is not. That neans Hashtable is thread safe while Hashmap is not.

Why would someonne use unsynchronized method or class iun place of synchronized ?
WHats the scenario in which unsynchronized ios preferred over synchronized ? Whats the trade off when we are using synchronized in place of unsynchronized ?

Thanks
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nirjari patel wrote:
Why would someonne use unsynchronized method or class iun place of synchronized ?
WHats the scenario in which unsynchronized ios preferred over synchronized ? Whats the trade off when we are using synchronized in place of unsynchronized ?

local variable. confused? somebody handover a method to you .
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization has a small performance overhead, so if it is not necessary, you'd rather not want to do it.

Most of the time you don't need synchronization - you need it only if your program has multiple threads that might be using the HashMap at the same time. So most of the time, the synchronization is done for nothing and it costs a little bit of performance.

If you do need a synchronized map, you can use the static method synchronizedMap(...) in class Collections to add synchronization to a regular map. Don't use the legacy collection classes, such as Hashtable. Example:

 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or use a class from the java.util.concurrent package such as ConcurrentHashMap
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!