aspose file tools
The moose likes Beginning Java and the fly likes Problem with SingleTon Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Problem with SingleTon" Watch "Problem with SingleTon" New topic
Author

Problem with SingleTon

jami siva
Ranch Hand

Joined: Oct 16, 2009
Posts: 55
Hi,

When I am trying to develop singleton class, It is not behaving like Singleton class.
Please check where I did wrong.
This is my SingleTon class.


To test this singleton i wrote this class,


After the result it is printing below output. But i expeced Instance is always 1 and object is same.
SingleTon Obj>>SingleTon@19821f
Instance 1
SingleTon Obj>>SingleTon@addbf1
Instance 2

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 5807
    
    5

Where are you setting your member variable to be non-null? In other words, how do you think you'll ever get into the else block in



Also, when posting code, please UseCodeTags(⇐click) so it will be readable.

And, finally, while this may be a useful academic exercise, the problem you're having only comes about because you're doing lazy instantiation. There is no good reason to do that. Simply instantiate at declaration time.



Or else just use the enum singleton approach.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
If you really want singleton behavior, one of the first things you need to do is prevent the class from being instantiated by any other class.
jami siva
Ranch Hand

Joined: Oct 16, 2009
Posts: 55
Thank Guys for your reply.

But If I do like this there is no singleton object, right?
Share your suggestions.

singletTonObj.clone();
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 3786
    
    1

Try it. As long as you haven't implemented Cloneable it won't work. And by default clone() is protected.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 4734
    
    7

jami siva wrote:But If I do like this there is no singleton object, right?
singletTonObj.clone();

Depends on how you implement clone(); but if you think about it, the call is nonsensical.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Problem with SingleTon
 
Similar Threads
review lock/unlock
Singleton class confusion
singleton pattern
how to work with interface in java?
2 different types of singleton