title: How to synchronize access on a static field of a super class?
body: <p>I have a class which contains a static field that acts like a singleton :</p>
  
  <pre><code>public class A {
  
      private static MyAPI instance = null;
  
      protected synchronized static MyAPI getAPI() throws Exception {
          if (instance == null){
              // init API;
          }
          return instance;
      }
  
      // other methods
  
  }
  </code></pre>
  
  <p>And I have multiple classes which inherit from the class A and needs to perform actions on the API. I work in a multi-threaded environment and the API can work once at a time, so I have to ensure that all the subclasses don't work on the API at the same time. To do that, I synchronize the super class when I access the API in subclasses :</p>
  
  <pre><code>public class B extends A {
  
      public void myMethod(){
          synchronized (A.class) {
              myAPI = getAPI();
              // do stuffs with myAPI
          }
      }
  }
  </code></pre>
  
  <p>With this solution, I lock the entire class instead of just the API instance, so the other methods of my class A are not available when a subclass work on the API and performances can be decreased.</p>
  
  <p>Do you think this is the best solution or do you know a better way ?</p>
  
  <p>Thanks.</p>