Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe implementation for Hash Map

First, I'll describe what I want and then I'll elaborate on the possibilities I am considering. I don't know which is the best so I want some help.

I have a hash map on which I do read and write operations from a Servlet. Now, since this Servlet is on Tomcat, I need the hash map to be thread safe. Basically, when it is being written to, nothing else should write to it and nothing should be able to read it as well.

I have seen ConcurrentHashMap but noticed its get method is not thread-safe. Then, I have seen locks and something called synchronized.

I want to know which is the most reliable way to do it.

like image 539
pratnala Avatar asked Nov 28 '22 11:11

pratnala


1 Answers

ConcurrentHashMap.get() is thread safe.

You can make HashMap thread safe by wrapping it with Collections.synchronizedMap().

like image 93
Peter Lawrey Avatar answered Dec 15 '22 02:12

Peter Lawrey