我正在创建一个示例演示程序,让我了解如何使用垃圾收集器在 Java 中释放静态变量和方法的引用?
我使用弱引用是为了不阻止垃圾收集器。
类样本
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;
}
}
类用户
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
}
}
最佳答案
静态字段与类相关联,而不是与单个实例相关联。
静态字段在装载类的类加载器卸载时被清除。在许多简单的程序中,这是永远不会发生的。
如果您希望字段与实例相关联并清理,那么实例将被清理,将它们设为实例字段,而不是静态字段。
关于java - 垃圾收集器是否处理 java 中的静态变量或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126833/