Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The appropriate solution depends very much on your particular problem. If all your threads can update any of the entries in the Map, then the first thing to try is <a href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow">ConcurrentHashMap</a>:</p> <p>In this case, the operation you described would be replaced with:</p> <pre><code>data = ... compute ... aHashMap.replace(skey, data); </code></pre> <p>Using ConcurrentHashMap solves the data race but one problem remains. If another thread would update the same key at the same time, one of the computations would be lost. If you are ok with this, great. Otherwise, you can:</p> <pre><code>do { oldData = aHashMap.get(skey); data = ... compute (maybe based on oldData) ... boolean success = aHashMap.replace(skey, oldData, data); } while(!success); </code></pre> <p>In this case, replace will only succeed if the data hasn't changed (and the replace would be atomic). If if fails, you can put everything in a do while loop to try again, maybe based on the updated value. </p> <p>Also, be careful not to have any side effects between the map get and replace. that computation should only create a brand new "data" object. If you update the "oldData" object or some other shared data you will get unexpected results.</p> <p>If you do have side effects, one approach is to have make a key-level lock like this:</p> <pre><code>synchronized(skey) { data = ... compute ... aHashMap.replace(skey, data); } </code></pre> <p>Even in this case, ConcurrentHashMap is still needed. Also, this will not stop some other code from updating that key in the map. All code that updates the key would need to lock on it. </p> <p>Also, this will not be thread-safe if you update oldData in "... compute ..." and the values are not unique within the map. If you do want to update oldData there, cover it with another synchronized.</p> <p>If this does the trick and your content with the performance, look no further.</p> <p>If the threads only update values, do not change the keys, then you might try converting your pairs to objects and use something different than a Map. For example, you could split the set of objects in several sets and then feed them to your threads. Or maybe use ParallelArray. But I might be digressing here... :)</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