I read in Book 4.3. Delegating thread safety in Concurrency in Practice use of final and Collections.unmodifiableMap(map) How does DelegatingVehicleTracker (p. 65 Goetz) return a "live" view? to delegate thread safety and i tried to create my example and saw the changes made by one thread are not getting reflected when map is returned.I am doing anything wrong
public class MapDem {
final Map<Integer, Integer> map;
final Map<Integer, Integer> map1;
public MapDem() {
map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
map1 = Collections.unmodifiableMap(map);
}
public Map<Integer, Integer> getMap() {
return Collections.unmodifiableMap(new HashMap<Integer, Integer>(map));
}
public void setValue(int key,int value){
map.replace(key, value);
}
public static void main(String args[]) {
MapDem demo = new MapDem();
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(demo.getMap());
}
});
t3.start();
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
demo.setValue(2, 40);
}
});
t4.start();
try {
t3.join();
t4.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(demo.getMap().size());
}
}
The output coming is
{1=10, 2=20}
2
or
{1=10, 2=40}
2
I want the map to see the updated value always.