6

I have a shared Map data structure that needs to be thread-safe. Is synchronized the most efficient way to read or add to the Map?

Thanks!

Edit: The data structure is a non-updatable cache, i.e. once it fills up it does not update the cache. So lots of writes initially with some reads then it is mostly reads

4 Answers 4

6

"Most efficient" is relative, of course, and depends on your specific situation. But consider something like ConcurrentHashMap if you expect there to be many threads working with the map simultaneously; it's thread safe but still allows concurrent access, unlike Hashtable or Collections.synchronizedMap().

Sign up to request clarification or add additional context in comments.

2 Comments

@LucaTampellini What do you mean by that? Did you read the documentation for the class so you understand the expected behavior?
sorry, i have read the documentation and saw that effectively: "Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove)."
3

That depends on how you use it in the app.

If you're doing lots of reads and writes on it, a ConcurrentHashMap is possibly the best choice, if it's mostly reading, a common Map wrapped inside a collection using a ReadWriteLock (since writes would not be common, you'd get faster access and locking only when writing).

Collections.synchronizedMap() is possibly the worst case, since it might just give you a wrapper with all methods synchronized, avoid it at all costs.

Comments

1

For your specific use case (non-updatable cache), a copy on write map will outperform both a synchronized map and ConcurrentHashMap.

See: https://labs.atlassian.com/wiki/display/CONCURRENT/CopyOnWriteMap as one example (I believe apache also has a copy on write map implementation).

1 Comment

0

synchronised methods or collections will certainly work. It's not the most efficient approach but is simple to implement and you won't notice the overhead unless you are access the structure millions of times per second.

A better idea though might be to use a ConcurrentHashMap - this was designed for concurrency from the start and should perform better in a highly concurrent situation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.