Sounds like something which possibly shouldn't be a Singleton.
You can unload a Class by removing any references to its ClassLoader and allowing both to be garbage collected. It's easier to redesign the Class so this isn't required though.
Joined: Jul 11, 2001
I agree with Dave - sounds like you probably shouldn't use the Singleton pattern.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Although James' solution works. If that's what you need you'd probably better with a factory to hand out the various instances - ie not a Singleton.
Joined: Aug 17, 2001
The clear() idea will not work, because some other class may have already obtained a reference. Then if it is cleared, the next caller will get a different instance and you will have two instances of your "Singleton".
There is no way to destroy a Singleton without breaking the Singleton property.
Sun Certified Programmer for the Java 2 Platform
Joined: Feb 18, 2005
As others have said, maybe a Singleton isn't appropriate here. If the number of instances of the class can go down to zero, then it's not a Singleton.
Instead of destroying the existing object and instantiating a new one, could you just change the internal state of the one that already exists? Or would that mess up any client objects that already have a reference to it?
What is this class/object used for?
Joined: Jan 29, 2003
What behavior do you expect? How would you know that it's been destroyed? What would happen?
I kinda liked James Carman's first response that when you ask for the instance you get nothing. That's a sign that it's no longer there even though it may be in memory a while before GC. If you had to load it from the class file again for some reason you could just use a new classloader (maybe a custom one) and populate your "theOnlyInstance" variable again.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Here's an interesting option... For the clear() method, move the instance to a weak reference. When the factory is called, it can try to get the reference back first. If it can't, then it can create a new one.