What does "synchronized" exactly do? Lock a function or lock an objects function?

speendo picture speendo · Jan 3, 2011 · Viewed 21.7k times · Source

I am wondering how exactly "synchronized" works in java.

Let's say I model a board-game that consists of a number of fields. I implement the fields as a class (Field) and the board as a class (Board) that contains a number of fields. Let's further say I modelled a method moveTo(Player pl) in Field, for a player to move to that field. Each player is represented by a thread.

Although all the threads should do some actions simultaneously (for example rolling their dices), there should only be one player that moves at a time.

How would I ensure that? Is it enough to make the method moveTo(Player pl) synchronized? Or would I need a cascading method in Board to make sure that only one player moves at a time? (Or is there a better solution)?

To bring it to the bottom line:
Would "synchronized" lock a method in EVERY object that has this method or would synchronized lock a method only in the object that is currently in use?
And if the second is the case: is there an easy way to lock a method for every object that has this method implemented?

Thank you!!!

Answer

jjnguy picture jjnguy · Jan 3, 2011

What I think you would want is the following:

class Field {

    // instance of the board
    private Board board; 

    public void moveTo(Player p){ 
        synchronized (board) {
            // move code goes here
        }
    }
}

This will make it so that per board, only one player is moving at a time. If you get the synchronization lock on the board, only one Field may enter the synchronized lock at a time. (Assuming one board)

If you simply wrote:

public synchronized void moveTo(Player p){ 

you would only be assuring that players couldn't move to the same Field at a time. This is because when a method is written with synchronized in the definition, it will lock at the object level. So, each instance of Field will be it's own lock object, and thus, players could still move at the same time as long as they weren't moving to the same Field.