垃圾收集器是否可以处理java中的静态变量或方法?

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时清除静态字段.在许多简单的程序中,这永远不会.

如果您希望将字段与实例关联并清理,则清除实例,将其设为实例字段,而不是静态字段.


Aru*_*nan 5

除了程序,回答你的问题

  1. 不会.方法不是垃圾收集的,因为它们首先不存在于堆中.

  2. 静态变量属于Class实例,一旦加载就不会被垃圾收集(对于大多数通用类加载器)