Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization - Static methods and Blocks

 
Senthil Kumar Sekar
Ranch Hand
Posts: 45
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also want to read Java Concurrency tutorial.
 
Senthil Kumar Sekar
Ranch Hand
Posts: 45
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic