title: In Java is there a way to directly make an attribute "synchronized"?
body: <p>If I have a an object with an attribute <code>private int i;</code>, 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 <code>i</code> directly, is there any way to declare that <code>i</code> is a "synchronized" attribute?</p>
  
  <pre><code>public class SharedObject {
  
    int i;
  
    synchronized public int getI() {
      return i;
    }
  
    synchronized public void setI(int i) {
      this.i = i;
    }
  
    public void badMethod() { &lt;&lt;-- added at later date by forgetful programmer
      // accidentally messes up 'i' because method is not "synchronized" !!
    }
  
  }
  </code></pre>
  
  <p>I thought maybe this could work, but it didn't:</p>
  
  <pre><code>public class SharedObject {
  
    synchronized int i; &lt;&lt;-- 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'
    }
  
  }
  </code></pre>