title: Multiple concurrent dynamic locks and timeouts if failure to acquire locks
body: <p>I have a use case where I need to lock on arguments of a function.</p>
  <p>The function itself can be accessed concurrently</p>
  <p>Function signature is something like</p>
  <pre><code>func (m objectType) operate(key string) (bool) {
      // get lock on &quot;key&quot; (return false if unable to get lock in X ms - eg: 100 ms)
      // operate
      // release lock on &quot;key&quot;
      return true;
  }
  </code></pre>
  <p>The data space which can be locked is in the range of millions (~10 million)</p>
  <p>Concurrent access to operate() is in the range of thousands (1 - 5k)</p>
  <p>Expected contention is low though possible in case of hotspots in key (hence the lock)</p>
  <p>What is the right way to implement this ? Few options I explored using a concurrent hash map</p>
  <ol>
  <li>sync.Map - this is suited for cases with append only entries and high read ratio compared to writes. Hence not applicable here</li>
  <li>sharded hashmap where each shard is locked by RWMutex - <a href="https://github.com/orcaman/concurrent-map" rel="nofollow noreferrer">https://github.com/orcaman/concurrent-map</a> - While this would work, concurrency is limited by no of shards rather than actual contention between keys. Also doesn't enable the timeout scenarios when lot of contention happens for a subset of keys</li>
  </ol>
  <p>Though timeout is a P1 requirement, the P0 requirement would be to increase throughput here by granular locking if possible.</p>
  <p>Is there a good way to achieve this ?</p>