In my application I have two threads. Thread 1 is transferring data to Thread 2. After the data is transferred the data in thread 1 is cleared within thread 2. Thread 1 goes on its merry way placing more data in the HashMap as it comes in to be transferred to Thread 2 later. In the meantime, Thread 2 does what it needs to do with the data. The code I have below is the part in thread 2 where that data transfer between threads happens. The entire application works just fine, but my questions is, is there a better way to make this copy of the thread 1 data for thread 2 without using the keyword new to create a whole new object?
I figure doing this might cause more garbage collections to occur? Should I not worry about this?
synchronized(this){
// Make a copy of the data map then clear it.
cachedData = new HashMap<String,ArrayList<Float>>(data);
data.clear();
}
So if you are accessing this
dataHashMapfrom multiple threads then you will have to have asynchronizedblock on every access. Just because you are grabbing a cached copy here does not mean that other threads get to use thedatawithout synchronization.If you want to have concurrent usage of
HashMapwithout having to synchronize around each usage then you should be using aConcurrentHashMap.Taking into account the cautions I mentioned above, if you want to take a snapshot of a
HashMapso you can work with the contents in a specific thread then the pattern you mention is fine and is often used. This pattern is also used when you need to iterate through aCollectionand modify it inside of the loop but without doing aniterator.remove().If you just need the keys or the values then make sure to take a copy of the
data.keySet()ordata.values()instead.