I have an object which contains tons of class fields (primitives and custom objects). This object is accessed in a way that its methods are executed by one thread at a time (no synchronization on the methods or on the class itself).
I would like to know the following: Even if the object is used by one thread at a time, it's still shared and its internal state must be shared along all the threads in order to prevent inconsistent state. The object is stored/retrieved from a collection, and the collection is accessed with synchronized methods.
Does synchronization on the collection (actually a map) guarantee that my object's fields will be visible for all the other threads? Please note that the object's fields are not volatile/synchronized.
Follows some code describing three ways of storing/retrieving the objects from the map. Once retrieved they belong to one and only one thread. Once put inside the map again they can be reusde by another thread.
Code:
public class POJO {
private int varA;
private CustomObj varB;
private String varC;
private AnOtherObj varD;
...
public void executeA(...) {
...
}
public void executeB(...) {
...
}
}
I can access the map in which POJO must be stored through these following methods which do not belong to POJO class.
public void updatePOJO(POJO pojo) {
//ReentrantLock
locker.lock();
map.put(pojo,Status.UPDATED);
locker.unlock();
}
public POJO getPOJO() {
//ReentrantLock
locker.lock();
POJO returnValue = map.keySet().iterator().next();
locker.unlock();
return returnValue;
}
public void updatePOJO_2(POJO pojo) {
synchronized(map){
map.put(pojo,Status.UPDATED);
}
}
public POJO getPOJO_2() {
synchronized(map) {
return map.keySet().iterator().next();
}
}
public void updatePOJO_3(POJO pojo) {
//Assuming map is a Collections.SynchronizedMap
map.put(pojo,Status.UPDATED);
}
public POJO getPOJO_3() {
//synchronization must occur since we ask objects through the iterator
synchronized(map) {
//Assuming map is a Collections.SynchronizedMap
return map.keySet().iterator().next();
}
}