What "singleton class" mean in this example
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   sabu_vs
Posted On:   Friday, June 20, 2003 03:03 AM

Hi below is the double checked locking pattern for creating singleton class. Below the code checks whether the "_instance" is null. If null the singleton.class object is locked using the synchronized keyword' Class Singleton{ public static Singleton getInstance() { if (_instance == null) { synchronized(Singleton.class) { if (_instance == null) _instance = new Singleton(); } } return _instance; } } My doubt is that how can we synchronize an object without creating it.Also I could not understand what "Singleton.class" means. is it an object of the current class?    More>>

Hi



below is the double checked locking pattern for creating singleton class. Below the code checks whether the "_instance" is null. If null the singleton.class object is locked using the synchronized keyword'




			

Class Singleton{

public static Singleton getInstance() {
if (_instance == null) {
synchronized(Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}

}




My doubt is that how can we synchronize an object without creating it.Also I could not understand what "Singleton.class" means. is it an object of the current class?

Could anyone give me a deatiled explanation.

Thanks

sabu

   <<Less

Re: What "singleton class" mean in this example

Posted By:   Benoit_Quintin  
Posted On:   Friday, June 20, 2003 08:11 AM

Have you tried reading a book on Java, like Bruce Eckel's Thinking In Java ?? Because all of your questions so far have been very basic ones, and the singleton pattern is probably not the best pattern to learn Java with, as it is not exactly the simplest, and can lead to many synchronisation issues; issues that are hard to debug, hard to find and hard to fix.

Re: What "singleton class" mean in this example

Posted By:   Anonymous  
Posted On:   Friday, June 20, 2003 04:08 AM

1/ In fact you can synchronize on any object! When you use synchronize(anObject), the anObject doesn't have to be (even if it usually is) part of the current method.



2/ Also, a class in Java is an object like any other object. A class is an instance of the class Class. The class Class is the meta-class of all classes. So, Singleton.class is an instance, therefore an object. This object is already existing in the system as it has been created when the class Singleton has been loaded in the VM.



Knowing 1 and 2, you can understand why this code is legal. This doesn't explain if it is clever or not. Actually, it all depends on the definition of your class Singleton. You are the only one to know what it does!



S.L.

www.liemur.com
About | Sitemap | Contact