3

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 null. 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)?

MySingleton.java

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();
        }
        System.out.println(defaultTimeStamp);
        return instance;
    }
}

SingletonTest.java

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

Output

2016-04-18 11:30:47.151
2016-04-18 11:30:47.151
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
yamori
  • 1,213
  • 4
  • 14
  • 27
  • 1
    The ClassLoader references the Class which references the static fields. If you no longer have a reference to any class (or instance of any class) in a classloader, the whole lot can be GCed. – Peter Lawrey Apr 18 '16 at 17:04

1 Answers1

3

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276