I just finished developing a java web service server for a distributed programming course I am attending. One of the requirements was to guarantee multi-thread safety to our project hence I decided to use ConcurrentHashMap objects to store my data. At the end of it all I am left with a question regarding this snippet of code:
public List<THost> getHList() throws ClusterUnavailable_Exception{ logger.entering(logger.getName(), "getHList"); if(hMap==null){ synchronized(this){ if(hMap==null){ hMap=createHMap(); } } } if(hMap==null){ ClusterUnavailable cu = new ClusterUnavailable(); cu.setMessage("Data unavailable."); ClusterUnavailable_Exception exc = new ClusterUnavailable_Exception("Data unavailable.", new ClusterUnavailable()); throw exc; } else{ List<THost> hList = new ArrayList<THost>(hMap.values()); logger.info("Returning list of hosts. Number of hosts returned = "+hList.size()); logger.exiting(logger.getName(), "getHList"); return hList; } } do I have to use the synchronized statement when creating the concurrenthashmap object itself in order to guarantee that the service will not have any unpredictable behavior in a multi-threaded environment?
hMapuntil this point? Why not just initialize it at construction time?hMap=createHMap();in the inner if and do some unmarshalling inside.