my code uses the following:
public class Obj{
public String someOperation(){...}
};
public class ClassA{
private Map<Integer, Object> m_MsgHash;
public boolean init()
{
m_MsgHash = Collections.synchronizedMap(new LinkedHashMap<Integer, Object>(1001, 1.0F, true));
}
private Object fetchFromHash(int Id)
{
return m_MsgHash.get(Id);
}
public void HandleMsg(int Id)
{
Object obj = fetchFromHash(Id);
// do some operation on obj needs to be synchronized ?
//synchronized (m_MsgHash) {
obj.someOperation();
//}
}
}
I understand from Java Doc that once iterating the my m_MsgHash i must use the synchronized keyword. but my question is, do i need to use the synchronized when using a fetched Object from my map ?
You do not need “synchronized” for simple operations on a synchronizedMap result, such as get. If the object referenced by obj is itself accessed from multiple threads, and modified by at least one of them, you need to make all accesses to it synchronized on the same object, or otherwise ensure multi-thread correctness.