title: How to synchronize multiple threads from accessing some common data
body: <p>I have three different threads which creates three different objects to read/manipulate some data which is common for all the threads. Now, I need to ensure that we are giving an access only to one thread at a time.</p>
  
  <p>The example goes something like this.</p>
  
  <pre><code>public interface CommonData {
     public void addData(); // adds data to the cache
     public void getDataAccessKey(); // Key that will be common across different threads for each data type
  }
  
  /*
  * Singleton class
  */
  public class CommonDataCache() {
     private final Map dataMap = new HashMap(); // this takes keys and values as custom objects
  }
  </code></pre>
  
  <p>The implementation class of the interface would look like this</p>
  
  <pre><code>class CommonDataImpl implements CommonData {
      private String key;
      public CommonDataImpl1(String key) {
         this.key = key;
      }
  
      public void addData() {
        // access the singleton cache class and add
      }
  
      public void getDataAccessKey() {
        return key;
      }
  }
  </code></pre>
  
  <p>Each thread will be invoked as follows:</p>
  
  <pre><code>CommonData data = new CommonDataImpl("Key1");
  new Thread(() -&gt; data.addData()).start();
  
  CommonData data1 = new CommonDataImpl("Key1");
  new Thread(() -&gt; data1.addData()).start();
  
  CommonData data2 = new CommonDataImpl("Key1");
  new Thread(() -&gt; data2.addData()).start();
  </code></pre>
  
  <p>Now, I need to synchronize those threads if and only if the keys of the data object (passed on to the thread) is the same.</p>
  
  <p>My thought process so far:</p>
  
  <p>I tried to have a class that provides the lock on the fly for a given key which looks something like this.</p>
  
  <pre><code>/*
  * Singleton class
  */
  public class DataAccessKeyToLockProvider {
      private volatile Map&lt;String, ReentrantLock&gt; accessKeyToLockHolder = new ConcurrentHashMap&lt;&gt;();
  
      private DataAccessKeyToLockProvider() {
      }
  
      public ReentrantLock getLock(String key) {
          return accessKeyToLockHolder.putIfAbsent(key, new ReentrantLock());
      }
  
      public void removeLock(BSSKey key) {
          ReentrantLock removedLock = accessKeyToLockHolder.remove(key);
      }
  }
  </code></pre>
  
  <p>So each thread would call this class and get the lock and use it and remove it once the processing is done. But this can so result in a case where the second thread could get the lock object that was inserted by the first thread and waiting for the first thread to release the lock. Once the first thread removes the lock, now the third thread would get a different lock altogether, so the 2nd thread and the 3rd thread are not in sync anymore.</p>
  
  <p>Something like this:</p>
  
  <pre><code>   new Thread(() -&gt; {
         ReentrantLock lock = DataAccessKeyToLockProvider.get(data.getDataAccessKey());
         lock.lock();
         data.addData();
         lock.unlock();
         DataAccessKeyToLockProvider.remove(data.getDataAccessKey());
      ).start();
  </code></pre>
  
  <p>Please let me know if you need any additional details to help me resolve my problem</p>
  
  <p>P.S: Removing the key from the lock provider is kind of mandatory as i will be dealing with some millions of keys (not necessarily strings), so I don't want the lock provider to eat up my memory</p>
  
  <p>Inspired the solution provided @rzwitserloot, I have tried to put some generic code that waits for the other thread to complete its processing before giving the access to the next thread.</p>
  
  <pre><code>public class GenericKeyToLockProvider&lt;K&gt; {
      private volatile Map&lt;K, ReentrantLock&gt; keyToLockHolder = new ConcurrentHashMap&lt;&gt;();
  
      public synchronized ReentrantLock getLock(K key) {
          ReentrantLock existingLock = keyToLockHolder.get(key);
          try {
              if (existingLock != null &amp;&amp; existingLock.isLocked()) {
                  existingLock.lock(); // Waits for the thread that acquired the lock previously to release it
              }
              return keyToLockHolder.put(key, new ReentrantLock()); // Override with the new lock
          } finally {
              if (existingLock != null) {
                  existingLock.unlock();
              }
          }
      }
  }
  </code></pre>
  
  <p>But looks like the entry made by the last thread wouldn't be removed. Anyway to solve this?</p>