Java concurrency with list map

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()

+3
7

listToSearch, , - .

, , ! add() -, .

, , , , , . JVM, . , , , .

, CopyOnWriteArrayList, . , , - , . javadoc .

+1

listToSearch ( "synchronized (listToSearch) {...}" ). , , ( innerListStore.putIfAbsent ).

+2

, , innerListStore.get(listName), , ConcurrentModificationException.

, , ListStore?

, , , , ? / ?

, , . / (.. ), .

+1

, , syncronizing listToSearch . Im 100%, ,

synchronized(listToSearch)
{

}
0

, , , CME (CopyOnWriteArrayList, ),

,

0

Guava

, , .

0

, boolean listEntryExists(String listName, String listEntry), , ? Map<String, Set<String>>, listEntryExists contains ( List, O (n) - ):

public boolean listEntryExists(String name, String entry) {
  SetString> set = map.get(name);
  return (set == null) ? false : set.contains(entry;
}

contains concurrency , .

add (, , , ), , ConcurrentMap.replace . , Guava ImmutableSet:

public boolean add(String name, String entry) {
  while(true) {
    SetString> set = map.get(name);
    if (set == null) {
      if (map.putIfAbsent(name, ImmutableSet.of(entry))
        return true
      continue;
    }
    if (set.contains(entry)
      return false; // no need to change, already exists
    Set<String> newSet = ImmutableSet.copyOf(Iterables.concat(set, ImmutableSet.of(entry))        
    if (map.replace(name, set, newSet)
      return true;
  }
}

, , ( ConcurrentMap). O (n) , O9n) . , - , , - .

0

All Articles