How to deep copy a hash map when working with multiple threads

In my application, I have two threads. In stream 1, data is transferred to Thread 2. After data is transferred, data in stream 1 is cleared in stream 2. Thread 1 continues its weight path, placing more data in the HashMap, since it enters the transfer for Thread 2 later. Meanwhile, Thread 2 does what it needs to do with the data. The code that I have below is part of thread 2, where data is transferred between threads. The whole application works very well, but my questions are: is there a better way to make this copy of thread 1 data for thread 2 without using the new keyword to create an entire new object?

I believe this could lead to garbage collection failures? Shouldn't I worry about this?

synchronized(this){
    // Make a copy of the data map then clear it.
    cachedData = new HashMap<String,ArrayList<Float>>(data);
    data.clear();
}
+3
source share
2 answers

So, if you are accessing this data HashMapfrom multiple threads, then you need to have a block synchronizedfor each access. Just because you grab a cached copy does not mean that other threads can use datawithout synchronization.

If you want simultaneous use HashMapwithout the need for synchronization around each use, you should use ConcurrentHashMap.

The whole application works fine, but my questions are: is there a better way to make this copy of thread 1 data for thread 2 without using the new keyword to create a whole new object?

, , HashMap, , , , . , Collection , iterator.remove().

, data.keySet() data.values().

+2

:

    synchronized(this){
        cachedData = data;
        data = new HashMap<String,ArrayList<Float>>();
    }

, , .

new ( , ).

+2

All Articles