I have a Restful webservice deployed in a non cluster standalone setup.. As we know multiple threads will be automatically spawned to cater to the requests from multiple clients to any of the endpoints defined in this webservice.. Note that there is no explicit spawning of threads from my end..
I am using HashMap inside one of the service/business methods ..I am iterating through the Map and in certain cases removing some data from the Map..
1.Are the multiple threads spawned for the multiple clients workinh on the same copy of the HashMap object ??
2.Is it recommended to use a ConcurrentHashMap in the above scenario even if each thread is using its own copy of the HashMap??
Putting the code snippet :-
Map<String,List<String>> method1(Item itm){
Map<String, FeatureEntity> featureEntityMap = itm.getFeatureEntities();// itm comes from method parameter
Map<String,List<String>> propertyFilterMap = new HashMap<String,List<String>>();//new Map to be constructed and returned by method
Set<String> keySet = featureEntityMap.keySet();
Iterator itr = keySet.iterator();
while(itr.hasNext()){
String featureName = (String) itr.next();
if(featureName.contains("."+lable.toLowerCase())){
String split [] = featureName.split("\\.");
if(split!=null && !LABEL_SPECIFIC_PROPERTIES.contains(split[0])){//based on condition data is deleted from featureEntityMap
List<String> itemList = Arrays.asList(featureEntityMap.get(featureName).getValueAsString().split("\\s*,\\s*"));
itr.remove();
propertyFilterMap.put(split[0],itemList );
}
}
}
return propertyFilterMap;
}
Question is "is it mandatory to use a ConcurrentHashMap for featureEntityMap ??"
The below answer is based on a generic understanding of your question, since the specific code for your case is missing.
Ok, so the short answer to your question about the hashMap "object" being used by multiple sessions or "threads" as you call, will not be the same.
Unless you have a singleton implemented, each "thread" will be creating it's own HashMap object.
Now when you say;
I am iterating through the Map and in certain cases removing some data from the Map
If what you are adding and removing from a map is completely contained within that session and has no effect on any of the other sessions (or threads), you should be okay.
But if you doing some kind of transactions using the map, that will affect other sessions, you need to think it over!
eg, you are fetching properties from a file, changing them and updating the file, or say you are doing some db updates or inserts based on your map content, Or any other such activity which will affect the logic of the other thread, then you will need to synchronise your HashMap (use a ConcurrentHashMap)