title: How to solve two threads and two instances of static variable scenario?
body: <p>In my spring project, in the <code>context.xml</code>, I have a bean defined for which I call the init method which creates an object <code>leaderSelector</code> which is static. </p>
  
  <pre><code>init() {
     leaderSelector= new customObject();
     leaderSelector.start();
  }
  </code></pre>
  
  <p>The <code>leaderSelector.start()</code> modifies the property <code>hasLeadership</code> of the object to <code>true</code>.</p>
  
  <p>The above init method is called whenever the server start-up.</p>
  
  <p>I also have a task scheduler which calls a different method in the same class <code>callJobs()</code>where I am accessing the object <code>leaderSelector</code>'s property <code>hasLeaderShip</code> which is <code>false</code>.</p>
  
  <pre><code>callJobs() {
      if(leaderSelector.hasLeaderShip()) {
          //do some important stuff
      }
  }
  </code></pre>
  
  <p>1.) The <code>init()</code> runs first and sets the <code>hasLeaderShip</code> property for the object <code>leaderSelector</code> to <code>true</code> in one thread.</p>
  
  <p>2.)The task scheduler calls <code>callJobs()</code> afterwards(in a different thread) and when it accesses the object <code>leaderSelector</code>'s <code>hasLeaderShip</code> property, it is <code>false</code>.</p>
  
  <p>The object <code>leaderSelector</code> is static. But two different instances of it are created. How should I get rid of the problem.</p>
  
  <p><strong>Complete program</strong></p>
  
  <pre><code>public class LeaderSelection extends LeaderSelectorListenerAdapter {
  
      private static LeaderSelector leaderSelector;
  
      @Autowired
      private JobExecutionSender jobExecutionSender;
  
      CuratorFramework client;
  
      String path = "";
  
      String zookeeperAddress = "/locks";
  
      @Value("${cds.dl.timeout}")
      private int sessionTimeout;
  
      public LeaderSelection() {
  
      }
  
      private void start() {
          leaderSelector.start();
      }
  
      public void init() {
          client();
          leaderSelector = new LeaderSelector(client, zookeeperAddress, this);
          leaderSelector.requeue();
          start();
      }
  
      public void callJobs() {
          if (leaderSelector.hasLeadership()) {
              jobExecutionSender.sendJobExecutions();
          }
      }
  
      @Override
      public void takeLeadership(CuratorFramework client) throws Exception {
          log.debug("Has LeaderShip:" + leaderSelector.hasLeadership());
      }
  }
  </code></pre>