title: Is it OK to use a string as a lock object?
body: <p>I need to make a critical section in an area on the basis of a finite set of strings. I want the lock to be shared for the same string instance, (somewhat similar to <a href="https://stackoverflow.com/questions/4192969/using-string-as-a-lock-to-do-thread-synchronization">String.Intern</a> approach).</p>
  
  <p>I am considering the following implementation:</p>
  
  <pre><code>public class Foo
  {
      private readonly string _s;
      private static readonly HashSet&lt;string&gt; _locks = new HashSet&lt;string&gt;();
  
      public Foo(string s)
      {
          _s = s;
          _locks.Add(s);
      }
  
      public void LockMethod()
      {
          lock(_locks.Single(l =&gt; l == _s))
          {
              ...
          }
      }
  }
  </code></pre>
  
  <p>Are there any problems with this approach? Is it OK to lock on a string object in this way, and are there any thread safety issues in using the <code>HashSet&lt;string&gt;</code>?</p>
  
  <p>Is it better to, for example, create a <code>Dictionary&lt;string, object&gt;</code> that creates a new lock object for each string instance?</p>
  
  <hr>
  
  <p><strong>Final Implementation</strong></p>
  
  <p>Based on the suggestions I went with the following implementation:</p>
  
  <pre><code>public class Foo
  {
      private readonly string _s;
      private static readonly ConcurrentDictionary&lt;string, object&gt; _locks = new ConcurrentDictionary&lt;string, object&gt;();
  
      public Foo(string s)
      {
          _s = s;
      }
  
      public void LockMethod()
      {
          lock(_locks.GetOrAdd(_s, _ =&gt; new object()))
          {
              ...
          }
      }
  }
  </code></pre>