gau*_*mar 7 java static garbage-collection reference
我正在创建一个示例演示程序,让我明白如何在使用垃圾收集器的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;
}
}
Run Code Online (Sandbox Code Playgroud)
类 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
}
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 18
静态字段与类关联,而不是单个实例.
在卸载类的ClassLoader时清除静态字段.在许多简单的程序中,这永远不会.
如果您希望将字段与实例关联并清理,则清除实例,将其设为实例字段,而不是静态字段.
| 归档时间: |
|
| 查看次数: |
13664 次 |
| 最近记录: |