title: Java synchronizing based on a parameter (named mutex/lock)
body: <p>I'm looking for a way to synchronize a method based on the parameter it receives, something like this:</p>
  
  <pre><code>public synchronized void doSomething(name){
  //some code
  }
  </code></pre>
  
  <p>I want the method <code>doSomething</code> to be synchronized based on the <code>name</code> parameter like this:</p>
  
  <p>Thread 1: doSomething("a");</p>
  
  <p>Thread 2: doSomething("b");</p>
  
  <p>Thread 3: doSomething("c");</p>
  
  <p>Thread 4: doSomething("a");</p>
  
  <p>Thread 1 , Thread 2 and Thread 3 will execute the code without being synchronized , but Thread 4 will wait until Thread 1 has finished the code because it has the same "a" value.</p>
  
  <p>Thanks</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on Tudor explanation I think I'm facing another problem:
  here is a sample of the new code:</p>
  
  <pre><code>private HashMap locks=new HashMap();
  public void doSomething(String name){
      locks.put(name,new Object());
      synchronized(locks.get(name)) {
          // ...
      }
      locks.remove(name);
  }
  </code></pre>
  
  <p>The reason why I don't populate the locks map is because name can have any value.</p>
  
  <p>Based on the sample above , the problem can appear when adding / deleting values from the hashmap by multiple threads in the same time, since HashMap is not thread-safe.</p>
  
  <p>So my question is if I make the <code>HashMap</code> a <code>ConcurrentHashMap</code> which is thread safe, will the synchronized block stop other threads from accessing locks.get(name) ??</p>