Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton  RSS feed

 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If i have a singleton ..class..and there are 2 threads that try to access the creation of the singletion instance...how would i limit the creation of only 1 instance..

Regards
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we talk about a Singleton in Java it's generally a "per ClassLoader" kind of Singleton. Presuming the single instance is a private static variable there's at least four different ways:

1. Properly synchronize the method that creates the instance.
2. Use a variable initializer.
3. Use a static initializer.
4. Use the Initialization On Demand Holder idiom.

Note that #1 excludes double-checked locking. Even with the new memory model that would require the variable to be volatile and would be just as slow or slower than proper synchronization.

#2 and #3 works because they will both be run when the class is initialized and that happens once.

#4 will work for the same reason #2 and #3 work but leverages lazy loading to get the benefits of lazy initialization without the need for synchronization.
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. use synchronized keyword to prevent multiple threads accessing the method.
2. go for eagerly created instance. This can be done by instantiating at the class loading time itself like

public class MySingleton{

private static MySingleton singleton = new MySingleton();

/*
rest you know

*/

}

This ensures that there will be only one instance and that will created during class loading time.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ken and Vishnu...!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!