title: Caching Reloading Put Block
body: <p>how can i block the put method when cache reloading is being called. </p>
  
  <p>Example: These are dummy classes not the actual.</p>
  
  <p>Caching class </p>
  
  <p>public class Class1 {</p>
  
  <pre><code>private static Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();
  
  public Class1() {
      for (int i = 0; i &lt; 20; i++) {
          map.put(i, ++i);
      }
  }
  
  public void reload() throws InterruptedException {
      Map&lt;Integer, Integer&gt; exist = map;
      System.out.println("are you waiting ");
      System.out.println("waiting over");
      map = new HashMap&lt;&gt;();
      for (Map.Entry&lt;Integer, Integer&gt; entry : exist.entrySet()) {
          map.put(entry.getKey(), entry.getValue());
      }
      for (int i = 100; i &lt; 120; i++) {
          map.put(i, ++i);
      }
  }
  
  public Map&lt;Integer, Integer&gt; getMap() {
      return map;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Class initializing the cache</p>
  
  <p>public class Class2 {</p>
  
  <pre><code>private static Class1 cache = new Class1();;
  
  public Class1 getCache() {
      return cache;
  }
  
  public void reload() throws InterruptedException {
      cache.reload();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>class using the cache</p>
  
  <p>package com.diaryreaders.corejava.algorithms.dp;</p>
  
  <p>public class Class3 {</p>
  
  <pre><code>public static void main(String[] args) {
      final Class2 klass = new Class2();
      Runnable runn1 = new Runnable() {
  
          @Override
          public void run() {
              int i = 50, j = 50;
              while (i &lt; 100) {
                  System.out.println("I am stuck due to lock");
                  klass.getCache().getMap().put(i++, j++);
                  System.out.println(klass.getCache().getMap());
              }
          }
      };
  
      Runnable runn2 = new Runnable() {
  
          @Override
          public void run() {
              try {
                  System.out.println("Calling reloading");
                  klass.reload();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      };
  
      Thread t1 = new Thread(runn1);
      Thread t2 = new Thread(runn2);
      t1.start();
      t2.start();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>As thread t2 is calling reloading, t1 should be blocked i.e cache put method be blocked till reloading completes</p>