我正在创建一个示例演示程序,让我了解如何使用垃圾收集器释放静态变量的引用、java 中的方法?
我使用弱引用来不阻止垃圾收集器。
班级Sample
public class Sample {
private static String userName;
private static String password;
static {
userName = "GAURAV";
password = "password";
}
public static String getUserName(){
return userName;
}
public static String getPassword(){
return password;
}
}
班级User
import java.lang.ref.WeakReference;
public class User {
public static void main(String[] args) {
/**
* Created one object of Sample class
*/
Sample obj1 = new Sample();
/**
* I can also access the value of userName through it's class name
*/
System.out.println(obj1.getUserName()); //GAURAV
WeakReference<Sample> wr = new WeakReference<Sample>(obj1);
System.out.println(wr.get()); //com.test.ws.Sample@f62373
obj1 = null;
System.gc();
System.out.println(wr.get()); // null
/**
* I have deallocate the Sample object . No more object referencing the Sample oblect class but I am getting the value of static variable.
*/
System.out.println(Sample.getUserName()); // GAURAV
}
}