简体   繁体   中英

ConcurrentHashMap.get() Iterator

I am trying to retrieve a subset of keys in an already-populated ConcurrentHashMap in java. The example code attached works for iterating through the get method for the specified elements, but my question is about whether iterating on the get is actually the most efficient use of ConcurrentHashMap?

This implementation seems no different than a normal HashMap - is the concurrency automatically built in? Is there a faster way to return all the elements for a subset of keys?

Looked into entrySet() method, but I am not entering the data into the map, it is pre-existing. Also looked into the forEach(), but it didn't seem to accept a subset of the complete map.

import java.util.*; 
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapgetExample1 { 
    public static void main(String[] args) 
    { 
        ConcurrentHashMap<Integer, String> maphash = new 
ConcurrentHashMap<Integer, String>(); 
        maphash.put(1, "AA"); 
        maphash.put(2, "BB"); 
        maphash.put(3, "CC"); 
        maphash.put(4, "DD"); 
        maphash.put(5, "EE"); 

        int[] keySubSet = {1, 2, 3};

        System.out.println("mappings are: " + maphash); 
       for (int i = 1; i < keySubSet.length + 1; i++){
        System.out.println(" Value : " + maphash.get(i)); 
           }

       } 
 } 

Code outputs correctly. But it doesn't seem "concurrent". Wondering if this is automatically an efficient implementation, or what would be.

From the javadoc :

A hash table supporting full concurrency of retrievals and high expected concurrency for updates.

Thus: misconception on your end. A ConcurrentHashMap does nothing by itself in parallel or multi-threaded ways.

It is simply a Map implementation that can be used by multiple threads in parallel. The ordinary HashMap ... can not (well: of course you can read/write to a HashMap in parallel, but then you are subject to race conditions and all the potential issues that arise when multiple threads operate on a container that isn't implemented to take the necessary precautions).

Long story short: a ConcurrentHashMap does not do what you assume it does.

Edit, given the comments by the OP:

Yes, you are correct, there is no API, neither in the Map interface, nor the HashMap or ConcurrentHashMap provide specific means to somehow retrieve a subset of keys/values, or key+value pairs. You can only retrieve keySet() , values() or entrySet() as a whole. You then have to iterate those to collect the things you want, or to throw aways what you don't want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM