Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton ThreadSafe

 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to make singleton Object without using syncronization code in getInstance() method.

 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If the signature of getInstance() method for the singleton is of the form:-



the method is thread safe due to the synchronized keyword taking care of concurrency issues. Drop the 'synchronized' and your getInstance() is potentially liable for creation of multiple instances due to concurrent invocation by multiple threads.

Cheers,
Raj.
 
Brice Giesbrecht
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To make your singleton, you can use a static initializer in your singleton.



To use it safely, you still have to make sure that the class remains threadsafe once you start adding functionality.
 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the above code loads the instance while startup, what if we need a lazy initialization, means we need to create the instance when client calls the getInstance() ... In that case we should not use synchronize the getInstance().... Any thoughts....???
 
Brice Giesbrecht
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the static initializer does actually cause synchronization but it is implicit and done by the jvm during the class loading and initialization routine. So, you could say I sort of cheated by suggesting that.

To guarantee that only one process is executing in the critical section of your method that will be doing the actual initialization (like getInstance), somewhere down the line you will need to use synchronization explicitly (or implicitly like the static init). You can bury it using many layers but it will be there.

I am curious about the aversion to using synchronization. Can you provide a little info on that?
 
shivendra tripathi
Ranch Hand
Posts: 263
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can find more info in the link below.

http://shivendra-tripathi.blogspot.com/2010/01/singleton-pattern.html
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic