This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Synchronization - Static methods and Blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchronization - Static methods and Blocks" Watch "Synchronization - Static methods and Blocks" New topic
Author

Synchronization - Static methods and Blocks

Senthil Kumar Sekar
Ranch Hand

Joined: Aug 08, 2010
Posts: 45


Static methods can be synchronized.
Does it means that the static data (which is the single copy for the entire class) is blocked?


synchronized(MyClass.class){

// some synchronized stuff
}

In the above code, static data of MyClass is locked?

Please let me know if i am on the wrong front.

Thanks.

Regards
Senthil Kumar Sekar
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1509
    
    5

Senthil Kumar Sekar wrote:In the above code, static data of MyClass is locked?

No. In given code, only code which lies within synchronized block is locked.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

You might also want to read Java Concurrency tutorial.
Senthil Kumar Sekar
Ranch Hand

Joined: Aug 08, 2010
Posts: 45

Ok then, Code in both the below blocks will be executed not more than one thread at a time.




What does someObject & MyClass.class in synchronized block indicate?

Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1509
    
    5

In the first code snippet, code is synchronized on object referred by someObject. So, if two(or more) threads are having same reference someObject, then only one thread at a time can enter in synchronized block.

In the second code snippet, code is synchronized on object referred by MyClass.class.

If you have any doubts regarding synchronization, I would suggest to go through link provided in previous post by Martin Vajsar.
 
GeeCON Prague 2014
 
subject: Synchronization - Static methods and Blocks