If I have a an object with an attribute private int i;
, I know I can make the getter and setter methods "synchronized" like so ... But since it's possible another method might be added later that accesses/changes i
directly, is there any way to declare that i
is a "synchronized" attribute?
public class SharedObject {
int i;
synchronized public int getI() {
return i;
}
synchronized public void setI(int i) {
this.i = i;
}
public void badMethod() { <<-- added at later date by forgetful programmer
// accidentally messes up 'i' because method is not "synchronized" !!
}
}
I thought maybe this could work, but it didn't:
public class SharedObject {
synchronized int i; <<-- this won't compile
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public void badMethod() {
// cannot mess up 'i', because 'i' is declared as 'synchronized'
}
}