Lets say that I have this class:
public SharedObject {
private int readOnlyField;
private int readWriteField;
public SharedObject(int field1, int field2) {
this.readOnlyField = field1;
this.readWriteField = field2;
}
public getField1() {...}
public synchronized getField2() {...}
public synchronized setField2(...) {...}
}
Can I have multiple threads that use these 3 methods concurrently?
Obviously I can with the last 2 synchronized methods, but I am not sure if getField1() can be executed concurrently with the other 2.
I think that the answer is yes, but just to be sure if I am missing some subtleties.
For
getField1
it can be executed simultaneously by 2 threads without any wait and synchronization. And since you are not having any setter, and its value is initialized upon object instantiation, so there are no change of dirty read as well.For
getField2
andsetField2
, no 2 threads and execute these methods at same time for the same instance ofSharedObject
.Hope this helps!!!