Discussions

EJB design: Singleton - Static and garbage collection

  1. Hi All,
    Can anyone explain me,

    How the singleton object doesn't get garbage collected or how to make it not collected?

    Is it because a static object, it doesnot get garbage collected??

    Thanks
    Sara
  2. Hi!

    Since you have a static variable like this:

    private static MySingleton instance = new MySingleton;

    you will always have a reference (in instance) to the object. Therefore, it will never be garbage collected.

    /Tomas
  3. Hi Tomas,
    Thanks for your response. So you mean if an object of type static it will never be garbage collected??
  4. As long as you keep a reference to an object, it will not be garbage collected. And the static variable is a reference.

    This also means you can have a sort of memory leaks in Java - if you keep references to objects you don't need. GC can only clean objects you don't have a reference to. I does not know if you really need the object or not.

    Example:
    - Create a Hashtable (or Vector) and store it as a public static variable.
    - Write one simple JSP page doing close to nothing.
    - Every time you access the page, create a large object and put it in the Hashtable. You can use the timestamp, new jav.util.Date(), as key.
    - Call the Web page several times, and sooner or later, you will get out of memory.
    The Hashtable has a reference to the large object, and GC will not see it.

    /Tomas
  5. Indeed an live reference to an object will make it ineligible for GC. The idea of static usage is to allow multiple instances to share the resource, probobly the information stored in this resource/object is not unique per class basis.

    Static variables have a bigger life times as they are initialised before the class is loaded and can consume memory till it is being referenced by any other object.

    Its really not a good iead to make evrything statis and one should be carefull while designing the classes.

    Secondly, Singleton and statis makes no sense, Singleton by iteself is one live instance in JVM.Creating static variables inside the singleton class is of no use as your synchronized getInstance() is going to check for an previous live referance to this singleton and return new instance only when the referance is null.

    Cheers
    VIJAY