0

I have read somewhere that these following fragments of code are equivalent regarding syncronized code:

public synchronized void printMsg() {
    System.out.println("synchronized");
}


public void printMsg() {
    synchronized(this) {
        System.out.println("synchronized");
    }
}

As far as I know though, when a Thread accesses a synchronized method on an Object, its non-synchronized methods are not locked, namely other Threads can access them using the same instance.

Observing the second fragment, I have the impression that since the code is synchronized on this, a Thread accessing that code acquires the lock on the Object.

My question is whether the other class methods can be accessed by other Threads when an Thraed maintains the lock excecuting the method printMsg() using the second code-snippet?

If no, the above methods are not exactly same. What is true?

Gray
  • 115,027
  • 24
  • 293
  • 354
arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • 2
    None of these are a dupllicate, especially not the first, just read a bit better the question – AlexWien Feb 12 '13 at 19:15
  • 1
    Related: http://stackoverflow.com/questions/4394976/what-is-the-difference-between-synchronizedthis-and-synchronized-method – assylias Feb 12 '13 at 19:42
  • Both `printMsg()` code fragments lock `this` and are functionally the same. They both lock `this`. The only time a thread blocks is if is calls `synchronized`. Just synchronizing on `this` doesn't stop other threads from calling (for example) the unsynchronized `toString()` method. – Gray Feb 12 '13 at 19:42

2 Answers2

2

Your first method implicitly grabs the lock on this so it is the same as your second method.

Any other method that is not synhronized, or synchronized on this in the method body, does not attempt to lock the object , and can be run concurrently by other threads.

nos
  • 223,662
  • 58
  • 417
  • 506
1

The above methods are equal. A thread doesn't need to acquire a lock on the object to access its methods unless they're marked with synchronized keyword - ergo, all other threads will execute these methods even if there's a thread holding synchronized (this) lock.

Ziemek
  • 121
  • 1
  • 3