title: When to use synchronized in Java
body: <p>I hope this is going to be enough information, so here it goes. If you need more info, lemme know in the comments.</p>
  
  <p>I have a class that has two inner classes. The inner classes each have two methods that call a method in the outer class. So, it looks like this:</p>
  
  <pre><code>public OuterClass {
      private boolean outerMethodHasBeenCalled = false;
  
      private void outerMethod() {
          if(!outerMethodHasBeenCalled) {
              // do stuff
          }
  
          outerMethodHasBeenCalled = true;
      }
  
      private FirstInnerClass {
          public void someMethod() {
              outerMethod();
          }
      }
  
      private SecondInnerClass {
          public void someOtherMethod() {
              outerMethod();
          }
      }
  }
  </code></pre>
  
  <p>It's important to note that:</p>
  
  <ul>
  <li>This is for an Android app. Instances of <code>FirstInnerClass</code> and <code>SecondInnerClass</code> are passed to a WebView as a JavaScript interface, so <code>someMethod</code> and <code>someOtherMethod</code> can be called at any time, in no particular order.</li>
  <li>I currently have a problem with the existing code (without the synchronized keyword) where <code>outerMethod</code> is called pretty much at the exact same time (I print out a log message, and they're timestamped to the 1000th of a second) by different objects. My app then 'does stuff' twice because <code>outerMethodHasBeenCalled</code> is still false when <code>outerMethod</code> was called. This is not okay, and it is exactly what I'm trying to prevent. My app should only 'do stuff' once and only once: the first time <code>outerMethod</code> is called.</li>
  <li>It might sound like I have multiple instances of <code>OuterClass</code>, but rest assured that it's  only one instance of <code>OuterClass</code>. </li>
  </ul>
  
  <p>It's important that my app 'does stuff' only the first time <code>outerMethod</code> gets called (I hope that's evident by now). All subsequent calls are essentially ignored. Whichever inner class calls <code>outerMethod</code> first -- doesn't matter.</p>
  
  <p>So, is it appropriate to use the synchronized keyword in this case?</p>