Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

reference - Does the garbage collector work on static variables or methods in 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.

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
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...