0

I checked implementation of System.out.println(), which is as follows and I have read this question.

public void println(int x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

According to above implementation the lock is on this object, so what is the advantage of using synchronized block instead of synchronized method in the above case?

Community
  • 1
  • 1
Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • As far as I know, I dont see any difference using synchronized method or block as we are locking on 'this'. Its upto the author I guess – HJK Apr 10 '15 at 08:26
  • I could also imagine some form of abstraction, because a synchronized method is directly visible as such to the developer, but a synchronized block is in a deeper layer of visibility so to say. – ceekay Apr 10 '15 at 08:33
  • There _is_ an advantage in using sync-block in that you have finer control over what you lock against (something finer-grained than `self`). However, that's irrelevant for this _particular_ case. In any case, the dupe-link details all that. – paxdiablo Apr 10 '15 at 08:35
  • @paxdiablo nice, that you point out things (s)he already mentioned in the first sentence ... – ceekay Apr 10 '15 at 08:38
  • @ceekay, assuming you meant the first commenter, I took the opportunity to expand on it since, though it points out no advantage _here,_ there _is_ an advantage in some cases. In fact, I prefer blocks since I'm used to the fine-grained control you get in pthreads, where locks are more on general resources rather than code sections (though you can certainly _use_ a piece of code as a resource). But the _main_ purpose of my comment was to explain my close-vote. – paxdiablo Apr 10 '15 at 08:46

1 Answers1

0

No advantage. They result in the same bytecode and are completely interchangeable.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Thanks for replying, I am thinking if developer had anything in mind while implementing `println` method. – Vishrant Apr 10 '15 at 08:27