I have a class, in which I have a state that consists of several fields-collections.
Now, I have methods that change that state. And there are methods that are reading it.
I want to use an explicit lock to guard state change modifications.
class Sample {
private final Map<String> a = new HashMap<>();
private final Map<String> b = new HashMap<>();
private final Map<String> c = new HashMap<>();
// protects the state of variables a,b,c so that the state modifications are atomic
private final Object lock = new Object();
...
// other fields
private void changeState(StateChange obj){
synchronized(lock){
changeA();
changeB();
changeC();
}
}
private State readState(){
synchronized(lock){
return buildStateFromABC();
}
}
}
If this class is accessed/modified in a multi-threaded environment, will each thread see up-to-date contents of fields a,b,c after entering a guarded area?
There is no direct correlation between the lock and those fields, or is there something?
I know that I can use an intrinsic lock here and just slap synchronized on methods, but I want to minimize the protected area.
What would be the preferred way of synchronizing here? On explicit lock object or on this?