yamori yamori - 1 year ago 32
Java Question

If a Singleton is not referenced by any other object, how or why does it stay alive?

Sorry if title is confusing, I will explain. I have a class using a Singleton pattern, and has a time-stamp value which is set at instantiation. In the example below, a second class instantiates this Singleton (and the default value). I then set the reference of that second class to

. I then retrieve the Singleton again and it still has the same default value. This is the desirable functionality for my needs, but I want to better understand why the Singleton stayed alive. Something to do with the JVM? Or would be there some sort of garbage collection which would delete the Singleton instance (and its original default value)?


import java.sql.Timestamp;

public class MySingleton {

private MySingleton() { }

private static MySingleton instance;
private static String defaultTimeStamp;

public static MySingleton getInstance() {
// Lazy instantation
if (instance == null) {
instance = new MySingleton();
// Assign the default value
java.util.Date date = new java.util.Date();
defaultTimeStamp = (new Timestamp(date.getTime())).toString();
return instance;


public class SingletonTest {
public static void main(String args[]) throws InterruptedException {
MySingleton mySingleton1 = MySingleton.getInstance();
mySingleton1 = null;
MySingleton mySingleton2 = MySingleton.getInstance();


2016-04-18 11:30:47.151
2016-04-18 11:30:47.151


The reference from the static field prevents the singleton from getting garbage collected. The singleton object is referenced from a static field in the MySingleton class. The class is referenced from the classloader. Once a class is loaded it doesn't get GC-ed until its classloader goes away.

Nulling out the variable that contains the reference returned from the call to getInstance has no effect on the reference contained in the static field instance.

Part of the problem with using static fields is the potential for memory leakage, that things referenced from them can hang around taking up memory for an indefinite time.