ConcurrentHashMap Examples

I read the article “ Java Theory and Practice: Creating a Better HashMap ” which gives an excellent overview of the implementation of ConcurrentHashMap.

I also found some discussions about this in Stackoverflow here .

I doubt it, although I had in my head what scripts / applications / places are, where ConcurrentHashMap is used.

thank

+3
source share
3 answers

I use it to quickly search from user IDs to user objects on a multi-threaded server, for example.

, . - , .

+1

ConcurrentHashMap , HashMap, , , .

+6

ConcurrentHashMap -.

  • . , 5 , .
  • () . , 5 , . , , . - (), - -.

:

public class ConcurrentHashMapExample {

    public static void main(String[] args) {

        //ConcurrentHashMap
        Map<String,String> myMap = new ConcurrentHashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "1");
        myMap.put("3", "1");
        myMap.put("4", "1");
        myMap.put("5", "1");
        myMap.put("6", "1");
        System.out.println("ConcurrentHashMap before iterator: "+myMap);
        Iterator<String> itr1 = myMap.keySet().iterator();

        while(itr1.hasNext()){
            String key = itr1.next();
            if(key.equals("3")) myMap.put(key+"new", "new3");
        }
        System.out.println("ConcurrentHashMap after iterator: "+myMap);

        //HashMap
        myMap = new HashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "1");
        myMap.put("3", "1");
        myMap.put("4", "1");
        myMap.put("5", "1");
        myMap.put("6", "1");
        System.out.println("HashMap before iterator: "+myMap);
        Iterator<String> itr2 = myMap.keySet().iterator();

        while(itr2.hasNext()){
            String key = itr2.next();
            if(key.equals("3")) myMap.put(key+"new", "new3");
        }
        System.out.println("HashMap after iterator: "+myMap);
    }
}

:

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$KeyIterator.next(HashMap.java:828)
    at com.test.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:44)

, HashMap a ConcurrentModificationException , , ! ( , : String key = itr1.next();)

0

Source: https://habr.com/ru/post/1772696/


All Articles