I have a java class that several threads access at once, and I want to make sure that it is thread safe. The class has one private field, which is a line map for line lists. I implemented the map as ConcurrentHashMap to ensure that recipients and litters are thread safe:
public class ListStore {
private Map<String, List<String>> innerListStore;
public ListStore() {
innerListStore = new ConcurrentHashMap<String, List<String>>();
}
...
}
So, given that receiving and transferring to the card is thread safe, my problem is with the lists stored on the Card. For example, consider the following method, which checks whether a given entry exists in the specified list in the repository (I skipped error checking for brevity):
public boolean listEntryExists(String listName, String listEntry) {
List<String> listToSearch = innerListStore.get(listName);
for (String entryName : listToSearch) {
if(entryName.equals(listEntry)) {
return true;
}
}
return false;
}
, , innerListStore.get(listName), , ConcurrentModificationException.
, , innerListStore listToSearch?
: . , . . add(), , listEntryExists() :
public void add(String listName, String entryName) {
List<String> addTo = innerListStore.get(listName);
if (addTo == null) {
addTo = Collections.synchronizedList(new ArrayList<String>());
List<String> added = innerListStore.putIfAbsent(listName, addTo);
if (added != null) {
addTo = added;
}
}
addTo.add(entryName);
}
, , , , , add()