Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>See a simple solution here <a href="https://stackoverflow.com/questions/5639870/simple-java-name-based-locks/5640671#5640671">Simple Java name based locks?</a></p> <p>EDIT: This solution has a clear happens-before relation from unlock to lock. However, the next solution, now withdrawn, doesn't. The <code>ConcurrentMap</code> javadoc is too light to guaranteed that.</p> <hr> <p>(<em>Withdrawn</em>) If you want to reuse your map as a lock pool, </p> <pre><code>private final V LOCK = ...; // a fake value // if a key is mapped to LOCK, that means the key is locked ConcurrentMap&lt;K,V&gt; map = ...; V lock(key) V value; while( (value=map.putIfAbsent(key, LOCK))==LOCK ) // another thread locked it before me wait(); // now putIfAbsent() returns a real value, or null // and I just sucessfully put LOCK in it // I am now the lock owner of this key return value; // for caller to work on // only the lock owner of the key should call this method unlock(key, value) // I put a LOCK on the key to stall others // now I just need to swap it back with the real value if(value!=null) map.put(key, value); else // map doesn't accept null value map.remove(key) notifyAll(); test() V value = lock(key); // work on value // unlock. // we have a chance to specify a new value here for the next worker newValue = ...; // null if we want to remove the key from map unlock(key, newValue); // in finally{} </code></pre> <p>This is quite messy because we reuse the map for two difference purposes. It's better to have lock pool as a separate data structure, leave map simply as the k-v storage.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload