Print all key/value pairs in a Java ConcurrentHashMap

前端 未结 6 724
清歌不尽
清歌不尽 2021-02-02 17:40

I am trying to simply print all key/value pair(s) in a ConcurrentHashMap.

I found this code online that I thought would do it, but it seems to be getting information ab

6条回答
  •  清歌不尽
    2021-02-02 17:47

    The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.

    To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:

    //Initialize ConcurrentHashMap instance
    ConcurrentHashMap m = new ConcurrentHashMap();
    
    //Print all values stored in ConcurrentHashMap instance
    for each (Entry e : m.entrySet()) {
      System.out.println(e.getKey()+"="+e.getValue());
    }
    

    Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.

    Hope this helps you.

提交回复
热议问题