Reputation: 414
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
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:
HashMap
(or consider LinkedHashMap
)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
Reputation: 81882
Upvotes: 3
Reputation: 4202
As its a single-threaded environment you can safely use HashMap.
Upvotes: 0
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
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