File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes synchronized (this) means? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronized (this) means?" Watch "synchronized (this) means?" New topic

synchronized (this) means?

Krishna Chhabra

Joined: May 15, 2007
Posts: 9

Not able to understand exactly that what does (this) means in below code

Carles Gasques
Ranch Hand

Joined: Apr 19, 2013
Posts: 199

The literates say that synchronize(this) inside a method is exactly the same that synchronize the method

because the synchronization in the 2 cases is over the object instance.

I would check now this with a class bytecode dump (just for fun),

Best regards,

Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 443

The last time I checked the actual byte code was different ...

The first had the byte code for entering the monitor, the second set the ACC_SYNCHRONIZED flag on the method, the effect may be the same but literally they are different, I wouldn't look at the byte code for that reason as it could confuse the issue. You could argue synchronized method is more efficient but I wouldn't get obsessed about it but if your intent is to synchronize the whole method I would definitely do that as its clearer.

See a more detailed explanation below ...

"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Krishna Chhabra wrote:Not able to understand exactly that what does (this) means in below code

It's telling us which lock we're going to obtain. The only thing that the synchronized keyword does¹ is to obtain the lock for the indicated object, blocking at that point in its execution until the lock is released if some other thread currently hodls it. That's all. When we do synchronized (this) that just means we're obtaining the lock for the "current" object.

¹Actually that's all it does in terms of mutual exclusion. It also provides some memory barrier effects for consistency and predictability of the values of shared variables, but that part isn't pertinent to your question.
I agree. Here's the link:
subject: synchronized (this) means?
It's not a secret anymore!