I have created three objects from class A. All of these three objects can update a value which is stored in private static volatile variable in class A. Updating this variable is done within a synchronized block with a certain criteria. I want to synchronize the block by using a lock-object.
So first the object are created in MainClass
A a1 = new A();
A a2 = new A();
A a3 = new A();
And after this the objects start to live their own lives. Here's a simplified example of my class A.
public class A{
private static volatile String sharedVariable;
Object lockObject = new Object();
private void updateVariable(String newValue){
//... some code
synchronized(lockObject){
//... code to check whether to update the value
sharedVariable = newValue;
}
}
Should I declare lockObject as private static volatile, if I want the synchronized block to be synchronized with all instances and all threads of class A? If I use the class (this) to synchronize the block, will it accomplish the same thing?
I think that with the above code the all of the instances of class A create their own lockObject and synchronized with it. Therefore the synchronization would only happen with threads within each instance (a1, a2 and a3). Is this correct?