Using Threads with a HashMap
Hi
I have a hashmap containing a series of objects. I need to perform calculations on these objects and write the updaste versions back into the hash map and time how long the calculations taker. Does anyone know how I can do this using threading?
I would like the thread to become active every few seconds, calculate and write back to the HashMap.
I guess I need to use a concurrent hash map has other threads will be writing to this hash map at the same time..
Thank you so much for any input you may be able to provide on this.
> Won't this block the entire Map while calculations
> are taking place? It would be better just to lock the
> objects in the Map I am calculating. I think
> ConcurrentHashMap will do this for me correct?
The Collections version synchronizes all access to the contents of the Map. A ConcurrentHashMap synchronizes gets against other gets, and puts against other puts, but doesn't synchronize gets against puts (someone correct me if I'm wrong). Using the Collections version will give you the means to let multiple threads access the Map without interfering with each other. Since only one thread can get an object from the Map at once, only one thread can work on the object, so you don't need to synchronize the objects themselves (if you make sure you only access the objects through the map methods).
I'm still unclear about what the OP wants to do. Consider these scenarios:
1. He want to access one or more value objects in the Map and update each one independently. You can imagine the objects having an update method. Other threads are allowed to see the map when only some of the objects have been updated.
2. He want to access one or more value objects in the Map and update each one independently. You can imagine the objects having an update method. Other threads are not allowed to see the map when only some of the objects have been updated. They should either find a map where all the values have their original state or all the values have their updated state.
There are many other possibilities. So which one is it?
> Scenario 2
In that case, I would have immutable objects (if practical) and never change the state of the map. Instead, I would would do something like this:
import java.util.*;
public class CopyOnWriteMapExample {
private Map < Key, Value > map;
private Object writeLock = new Object();
CopyOnWriteMapExample() {
setMap(new HashMap<Key, Value>());
}
private synchronized void setMap(Map < Key, Value > m) {
map = Collections.unmodifiableMap(m);
}
public synchronized Map <Key, Value > getMap() {
return map;
}
public void operation(Object parameter) {
synchronized (writeLock) {
Map < Key, Value > newMap = new HashMap<Key, Value>(getMap());
for(Map.Entry < Key, Value > e : newMap.entrySet()) {
e.setValue(e.getValue().mutate(parameter));
}
setMap(newMap);
}
}
}
class Value {
public Value mutate(Object parameter) {
//returns new value with new state
}
}