Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronizing block or method ?  RSS feed

 
Sheikh Sadiruddin
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have class like below



I want to make getInstance() method thread safe.
I can do it using 'synchronized' keyword like this.


But if i want to make it block level synchronization , then which block of code should i make synchronized?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'd add a new block, enclosing the whole contents of your method, and put "synchronized" before it. You need an object to synchronise on; you can use the Class object, but I prefer to use a specially-created lock object. Something like: -



Note that the correct word is "singleton", not "SingleTone". Also, the whole idea of singletons is not very well-regarded, these days. You should try to avoid using singletons in your applications, whenever there's a way to do so.
 
Sheikh Sadiruddin
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Peter for your reply.

My question is what is the difference in that case where i put synchronized in the method level and you put in the block level (all codes within the method).
It seems to me that there is no difference as such.
I am just not able to understand this two aspects of synchronization.
[ March 13, 2008: Message edited by: Sheikh Sadiruddin ]
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Peter's example was rewritten to sync on the class object for your singleton (as static method) then the answer would be none (well nearly none). Peter's example shows you can chose the object to sync on, rather than being forced to sync on the class object (static method) or this object (none static method), which has its uses.

I suspect for your simple singleton class urposes the answer is no difference.

The other subtle difference is in the byte code in that the last time I ran say a synchronized method (non static) and one synchronized by this for the whole method, one resulted in the ACC_Synchronized flag set on the method call the other byte code for the synchronization, if this happens for all javac's I don't know and if the nice fancy Java 6 optimizations (escape analysis etc) would perform differently I don't know, different code paths but you'ed like to think not :-)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!