Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd suggest you not synchronize on entire method <code>put</code>. But <strong>synchronize only on on specific cell</strong>. In code below, I'll describe how to do that:</p> <pre><code>class ConcurrMattr { private ConcurrentHashMap&lt;Integer, Lock&gt; locks = new ConcurrentHashMap&lt;Integer, Lock&gt;(); public Cell put( CellCoords key, Cell arg1 ) { // get or create lock for specific cell (guarantee its uniqueness) Lock lock = this.locks.putIfAbsent( coords.hash % 64, new ReentrantLock() ); // 64 threads may concurrently modify different cells of matrix try { // lock only specific cell lock.lock(); // do all you need with cell return ...; } finally { // unlock cell lock.unlock(); } } } // Immutable class to represent cell coordinates class CellCoords { public final int x; public final int y; public final int hash; public CellCoords( int x, int y ) { this.x = x; this.y = y; this.hash = this.calcHash(); } private int calcHash() { int result = 31 + this.x; return 31 * result + this.y; } } </code></pre> <p>So you may synchronize <code>read/write</code> methods on specific cell, while <strong>other part of matrix will be accessible to other threads</strong>.</p> <p>Look at javadoc for <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow"><code>ConcurrentHashMap</code></a> and for <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html" rel="nofollow"><code>Lock</code></a></p> <p><strong>P.S.</strong> <br/> You may notice, that <code>CellCoords</code> field <code>hash</code> has type <code>int</code>. To avoid growth of locks map size till 2^31, you have to <strong>limit range of hashes</strong>. For example: <code>(coords.hash % 64)</code> - allows only 64 concurrent threads to work with entire matrix.</p> <p>P.P.S. Might be interesting article for you: <a href="http://www.ibm.com/developerworks/java/library/j-jtp08223/" rel="nofollow">http://www.ibm.com/developerworks/java/library/j-jtp08223/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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