Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think your problem is that you call <code>swap(.., ..)</code> from multiple threads and the <code>swap</code> (and <code>lockedIndex</code>) method is not thread safe since the member (<code>lock1</code> and <code>lock2</code>) variables could be set by another thread - and you would <code>unlock</code> some other index that you did not lock.</p> <hr> <p>Using <code>tryLock</code> could be tricky, what would you do if you cannot get the lock?</p> <p>I would go for the solution the guys over at the forum described - locking the indexes in a perticular order for more information about the problem you have run into see <a href="http://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="nofollow">Dining philosophers problem</a>.</p> <p>Here is your code re-written to use <code>lock()</code> instead:</p> <pre><code>class ShuffleBase { private int[] data; private ReentrantLock[] locker; public ShuffleBase(int[] data) { this.data = data; this.locker = new ReentrantLock[data.length]; for (int x = 0; x &lt; data.length; x++) this.locker[x] = new ReentrantLock(); } public void swap(int a, int b) { // check if we have to do sothing if (a == b) return; // set the order (we want to lock lower indexes first!) if (b &lt; a) { int tmp = b; b = a; a = tmp; } // lock them in sequence (first the lower, then the higher index) locker[a].lock(); locker[b].lock(); // do the swap int tmp = data[b]; data[b] = data[a]; data[a] = tmp; // unlock locker[b].unlock(); locker[a].unlock(); } public void display() { for (int i = 0; i &lt; locker.length; i++) locker[i].lock(); System.out.println("Swapped array: " + Arrays.toString(data)); for (int i = 0; i &lt; locker.length; i++) locker[i].unlock(); } } </code></pre>
 

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