ManthanB
ManthanB

Reputation: 414

Does a Collection which is Thread Safe have to be Synchronized?

I wanted to use Collection for only single threaded environment and I am using a HashMap that is synchronized.

However, I still doubt if it is thread safe to have it synchronized or not.

Upvotes: 0

Views: 223

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1500145

If you're only using a single thread, you don't need a thread-safe collection - HashMap should be fine.

You should be very careful to work out your requirements:

  • If you're really using a single thread, stick with HashMap (or consider LinkedHashMap)
  • If you're sharing the map, you need to work out what kind of safety you want:
    • If the map is fully populated before it's used by multiple threads, which just read, then HashMap is still fine.
    • Collections.synchronizedMap will only synchronize each individual operation; it still isn't safe to iterate in one thread and modify the map in another thread without synchronization.
    • ConcurrentHashMap is a more "thoroughly" thread-safe approach, and one I'd generally prefer over synchronizedMap. It allows for modification during iteration, but doesn't guarantee where such modifications will be seen while iterating. Also note that while HashMap allows null keys and values, ConcurrentHashMap doesn't.

Upvotes: 4

Jens Schauder
Jens Schauder

Reputation: 81882

  1. the standard java HashMap is not synchronized.
  2. If you are in a single threaded environment you don't need to worry about synchronization.

Upvotes: 3

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

As its a single-threaded environment you can safely use HashMap.

Upvotes: 0

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20741

The commonly used Collection classes, such as java.util.ArrayList, are not synchronized. However, if there's a chance that two threads could be altering a collection concurrently, you can generate a synchronized collection from it using the synchronizedCollection() method. Similar to the read-only methods, the thread-safe APIs let you generate a synchronized collection, list, set, or map. For instance, this is how you can generate a synchronized map from a HashMap:

  Map map = Collections.synchronizedMap(new HashMap());
  map.put(...

Upvotes: 0

MayurB
MayurB

Reputation: 3649

For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency

Upvotes: 3

Related Questions