Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing instance of a singleton in java

I am using a singleton created by the initialization-on-demand holder idiom. When I´m done, I would like to "return" the singleton so that it can be used by other programs. Can I do this as follows...

Creating the Singleton

public class MyObject{
    private MyObject(){}
    private static class Holder{
       private static final MyObject INSTANCE = new MyObject();
    }
    public static MyObject getInstance(){
       return Holder.INSTANCE;
    }
}

somewhere else I use this by

MyObject myObject = MyObject.getInstance();
// do something
myObject = null;
System.gc();
like image 757
tip Avatar asked Dec 08 '25 10:12

tip


1 Answers

This accomplishes nothing:

myObject = null;

The singleton object will always be referenced by the final INSTANCE field in the Holder class, and it never will be GCd.

In fact, that's what "singleton" means. A "singleton" is a class for which only one instance is ever created, and the instance is never destroyed. If you want something else, then call it something else. Don't call it "singleton."

I bet you either want to use some form of mutual exclusion to prevent more than one thread from using the singleton at the same time, or else you want what @Newerth said: an object pool.


Also, this is obsolete: System.gc(); In the very early days of Java, it would bring everything else to a halt while the GC reclaimed all of the unused objects from the heap, but modern JVMs do continuous garbage collection in the background. The documentation for System.gc() has been changed to say that it's only a suggestion.

like image 147
Solomon Slow Avatar answered Dec 09 '25 22:12

Solomon Slow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!