0
class public Test
{
    private int counter;

    public synchronized change()
    {
        counter++;
    }

    public change2()
    {
        synchronized(this){
            counter--;
        }
    }

}

Can we call change and change2 at the same time?

Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
IceKing
  • 29
  • 1
  • 1
  • 5

1 Answers1

3

Names have nothing to do with it. What is being locked is the object (not the variable, not the reference).

If a thread has started executing a block which synchronizes on an object, any other thread that tries to synchronizes on the same object will block and wait until that original thread completes the execution of its block.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724