File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronized (this) means?" Watch "synchronized (this) means?" New topic
Author

synchronized (this) means?

Krishna Chhabra
Greenhorn

Joined: May 15, 2007
Posts: 9
Hi,

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



Thanks
Carles Gasques
Ranch Hand

Joined: Apr 19, 2013
Posts: 199
    
    1
Hi,

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: 420
    
    2

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 ...

http://stackoverflow.com/questions/9117115/why-synchronized-keyword-does-not-create-monitor-enter-every-time


"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
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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: http://aspose.com/file-tools
 
subject: synchronized (this) means?