2

I just wanted to be sure that I understood the following right.

  1. The synchronized keyword on methods forbids two such methods to be run simultaneously on one instance of the class.
  2. The synchronization object is the instance in question.

If this is true the following example should be right

class Example
{
  public synchronized void method1()
  {
    // mark 1 - never here when other thread at mark 2 or 4
  }

  public synchronized void method2()
  {
    // mark 2 - never here when other thread at mark 1 or 4
  }

  public void method3()
  {
    // mark 3 - may be (!) here when other thread at mark 1, 2 or 4
    synchronized (this)
    {
      // mark 4 - never here when other thread at mark 1 or 2
    }
  }
}

Thx for a 'yes' or falsification. b

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
u_b
  • 93
  • 6

2 Answers2

3

Your understanding is correct.

Take a look at the following for further discussion: Avoid synchronized(this) in Java?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • your link is interesting, although 'dont use sync(this)' seems to me like the regular rule of thumb that is not universally true... – u_b Apr 13 '11 at 11:47
2

What you've said is correct.

And to add one thing, if the method is a static method, the Class is the lock.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52