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