Singleton Pattern
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Srikanth_Basavaraju
Posted On:   Wednesday, September 28, 2005 01:43 AM

I know that the general convention in which the single pattern is created is using getInstance() method. But can I say that the following code 1. doesnt implement singleton correctly ? 2. The class in the below way is not a singleton ? 3. Is static geInstance() kind of method a must for implementing singleton ? Thanks public MyClass { public static instance_already_created = false; public MyClass() { if (!instance_already_created) { instance_already_created = true; } else { throw new CustomException(); } } }    More>>


I know that the general convention in which the single pattern is created is using getInstance() method.



But can I say that the following code 1. doesnt implement singleton correctly ? 2. The class in the below way is not a singleton ? 3. Is static geInstance() kind of method a must for implementing singleton ?

Thanks



public MyClass {


public static instance_already_created = false;


public MyClass() {


if (!instance_already_created) {


instance_already_created = true;


}

else

{


throw new CustomException();


}


}


}


   <<Less

Re: Singleton Pattern

Posted By:   Jani_Kaarela  
Posted On:   Wednesday, September 28, 2005 02:46 AM



  1. Yes, it does not implement the singleton pattern correctly.

  2. ... and thus it is not a singleton.

  3. The name of the method doesn't matter, but it must be static and synchronized.




The problem with the above implementation is, that instance_already_created is not synchronized - a thread could observe it in false state, proceed to the if-block, and then, another thread could observe it before it has been changed to true. You could possibly fix it by switching to a Boolean object and synchronize the contents of the constructor on it, but on the other hand, why not stick with the tried and true static synchronized getInstance()?

About | Sitemap | Contact