Search code examples
javamultithreadingthread-safetyconcurrenthashmap

Concurrent HashMap iterator:How safe is it for Threading?


I used concurrent hashmap for creating a matrix. It indices ranges to 100k. I have created 40 threads. Each of the thread access those elements of matrices and modifies to that and write it back of the matrix as:

ConcurrentHashMap<Integer, ArrayList<Double>> matrix = 
    new ConcurrentHashMap<Integer, ArrayList<Double>>(25);

for (Entry(Integer,ArrayList<Double>)) entry: matrix.entrySet())
    upDateEntriesOfValue(entry.getValue());     

I did not found it thread safe. Values are frequently returned as null and my program is getting crashed. Is there any other way to make it thread safe.Or this is thread safe and i have bug in some other places. One thing is my program does not crash in single threaded mode.


Solution

  • The iterator is indeed thread-safe for the ConcurrentHashMap.

    But what is not thread-safe in your code is the ArrayList<Double> you seem to update! Your problems might come from this data structure.

    You may want to use a concurrent data structure adapted to you needs.