垃圾收集器在java中的静态变量或方法上工作吗? [英] Does the garbage collector work on static variables or methods in java?

查看:138
本文介绍了垃圾收集器在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;
    }
}

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
    }

}


推荐答案

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

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天全站免登陆