PeterK
PeterK

Reputation: 1723

Multi threaded access to map object that won't be modified after creation

What is the best practice for creating a Map<> object that will be access from multiple threads, but that will not be modified after initialization?

Would it be:

  1. use a ConcurrentHashMap<> object
  2. create a normal HashMap<> object and wrap this in a Collections#unmodifiableMap call? Only retaining a reference to the unmodifiableMap and not the original HashMap<>.
  3. something else.

Thanks, Peter

Upvotes: 0

Views: 74

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

I believe (of the presented options) option number 2 is likely to be far more efficient.

A CuncurrentHashMap per the Javadoc, provides A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.

It has to perform work to provide that, just keep the immutable Map instance and let multiple readers access it.

Upvotes: 2

noMAD
noMAD

Reputation: 7844

Why don't you try an ImmutableMap? Once created cannot be modified so doesn't matter how many threads try to read in parallel.

Upvotes: 2

Related Questions