I need to map objects inside Servlet. Is ConcurrentHashMap a reliable choice to use? Will all requests get requested object from map or will there be failures?
public class MyServlet extends HttpServlet {
private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
public void doGet(HttpServletRequest request, HttpServletResponse response) {
// use map
map.get("myObjectName");
}
}
The purpose of a
ConcurrentHashMapis to allow retrieval without locking. It is suitable for multi-threaded programs that have lot of reads and very few writes.You wrote
If by that you mean that the map does not change after servlet initialization, then you don’t need a
ConcurrentHashMapat all. You can use plain oldHashMap. Even better would be to convert it to a non-modifiable map by usingCollections.unmodifiableMap.