This seems to be a pretty frequent question though I didn’t find one. Suppose I have this piece of code:
public class MyClass {
private AnotherClass mField;
public void changeOne(AnotherClass newOne) {
// <...> lines of code here
synchronized (mField) {
mField = newOne;
}
// <...> lines of code here
}
public void changeTwo(AnotherClass newTwo) {
// <...> lines of code here
mField = newTwo;
// <...> lines of code here
}
}
Let’s say changeOne() and changeTwo() are called from different threads. Is it enough to have a synchronized block in changeOne() to protect mField from changing by changeTwo()? Or I need to explicitly wrap each place where mField is changed into the synchronized block? (please leave behind synchronized methods and others).
You need to explicitly synchronize all modifications to
mFieldusing either synchronized block (or) synchronized method. Otherwise more than one thread can changemFieldby executing changeTwo at a time.EDIT: As Tedd Hopp suggested, if variable is not volatile reads also need to synchronized and lock you get should be on same object.