垃圾收集器是否适用于 Java 中的静态变量或方法? [英] Does the garbage collector work on static variables or methods in java?

查看:17
本文介绍了垃圾收集器是否适用于 Java 中的静态变量或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个示例演示程序,以便让我了解如何使用垃圾收集器释放 Java 中静态变量和方法的引用?

I am creating a sample demo program for make me understand that how can I deallocate the reference of static variables, methods in java using garbage collector?

我使用弱引用是为了不阻止垃圾收集器.

I am using Weak Reference for not preventing the garbage collector.

示例

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
    }

}

推荐答案

静态字段与类相关联,而不是单个实例.

static fields are associated with the class, not an individual instance.

静态字段在持有类的 ClassLoader 卸载时被清理.在许多简单的程序中,这从来都不是.

static fields are cleaned up when the ClassLoader which hold the class unloaded. In many simple programs, that is never.

如果您希望字段与实例相关联并被清理,那么实例将被清理,请将它们设为实例字段,而不是静态字段.

If you want the fields to be associated with an instances and cleaned up then the instance is cleaned up, make them instance fields, not static ones.

这篇关于垃圾收集器是否适用于 Java 中的静态变量或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆