I have a ConcurrentHashMap object which is shared by multiple threads to access:
Map<String, MyConnection> myMap = new ConcurrentHashMap<String, MyConnection>();
The class MyConnection contains some connection to the datasource.
At a later stage, I need to iterate the ConcurrentHashMap, call MyConnection.close() method and remove it from the Map. Something like this:
for(String key : myMap.ketSet()) {
MyConnection connection = myMap.get(key);
connection.close();
myMap.remove(key);
}
However, the myMap is shared by multiple thread, which can be adding, removing from the ConcurrentHashMap at the same time.
How can I make sure the for loop above is thread safe to run? There is not requirement that the loop has to remove all the entries in the map. The loop only needs to remove all the elements at the time myMap.keySet() is called. Any subsequent elements added to the map does not have to be removed.
Obviously I can lock the entire for loop and prevents other thread from touching the map, but I think it is not performance efficient.
Can someone please share your opinion?
EDIT1 : And How about this? Is this thread safe?
for(MyConnection connection : myMap.values()) {
connection.close();
myMap.remove(connection.getId());
}
Each connection object has a ID, which is also the key of that entry.