我正在创建一个示例演示程序,以便让我了解如何使用垃圾收集器在 java 中释放静态变量、方法的引用?
我使用弱引用是为了不阻止垃圾收集器。
Class 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;
}
}
Class 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
}
}
静态字段与类相关联,而不是与单个实例相关联。
当保存类的类加载器卸载时,静态字段将被清除。在许多简单的程序中,这永远不会。
如果您希望字段与实例关联并清理,那么实例就会被清理,请将它们设置为实例字段,而不是静态字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)