Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I added another answer because I can't yet add comments to other people posts.</p> <ul> <li>In fact, synchronization is for code, not objects or data. The object reference used as a parameter in synchronized block represent the lock.</li> </ul> <p>so if you have code like :</p> <pre><code>class Player { // Same instance shared for all players... Don't show how we get it now. // Use one dimensional board to simplify, doesn't matter here. private List&lt;Player&gt;[] fields = Board.getBoard(); // Current position private int x; public synchronized int getX() { return x; } public void setX(int x) { synchronized(this) { // Same as synchronized method fields[x].remove(this); this.x = x; field[y].add(this); } } } </code></pre> <p>Then Despite beeing on synchronized block the access to field is not protected because the lock is not the same (it being on different instances). So your List of Players for your board can become inconsistent and cause runtime exceptions.</p> <p>Instead if you write the following code, it will work because we have only one shared lock for all players :</p> <pre><code>class Player { // Same instance shared for all players... Don't show how we get it now. // Use one dimensional board to simplify, doesn't matter here. private List&lt;Player&gt;[] fields; // Current position private int x; private static Object sharedLock = new Object(); // Any object's instance can be used as a lock. public int getX() { synchronized(sharedLock) { return x; } } public void setX(int x) { synchronized(sharedLock) { // Because of using a single shared lock, // several players can't access fields at the same time // and so can't create inconsistencies on fields. fields[x].remove(this); this.x = x; field[y].add(this); } } } </code></pre> <p>=> Be sure to use only a single lock to access all the players or your board's state will be inconsistent.</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.
    3. 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