如果我再次使用它,“最终”对象会发生什么?

时间:2015-01-12 06:50:02

标签: java garbage-collection

好吧,我尝试再次提供最终对象 。我知道(来自oracle docsfinalize()将不会再次调用public class Solution { static ThreadGroup stg = null; static Solution ss = null; protected void finalize() throws Throwable { System.out.println("finalized"); System.out.println("this : " + this); ss = this; } public static void main(String[] args) { Solution s = new Solution(); s = null; System.gc(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(ss); ss = null; // My question. What happens now?. Solution@7f5f5897 has just become unreachable. Will it be GCed without "finalize()" being called on it? (looks like that..). If yes, then how can I find out when exactly has it become eligible for gc (Please don't tell me to look at source code "==null" check :P) System.gc(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 。但如果它变得无法访问会发生什么? 什么时候会被GC?

代码:

finalized
this : Solution@7f5f5897   // printed in finalize()
Solution@7f5f5897  // printed in main()

}

O / P:

{{1}}

1 个答案:

答案 0 :(得分:4)

是的,它会在第二次无法访问时进行GC,除了finalize不会再次被调用。

您可以使用WeakReference进行确认。

static WeakReference<Solution> ref;

public static void main(String[] args) {
    Solution s = new Solution();

    s = null;
    System.gc();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(ss);
    ref = new WeakReference<Jackson>(ss);
    ss = null; // My question. What happens now?. Solution@7f5f5897 has just become unreachable. Will it be GCed without "finalize()" being called
               // on it? (looks like that..). If yes, then how can I find out when exactly has it become eligible for gc (Please don't tell me to
               // look at source code "==null" check :P)
    System.out.println(ref.get()); // (hopefully) prints object
    System.gc();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(ref.get()); // prints null
}

所以WeakReferenc被清除,表明该对象是GC。 (从技术上讲,当对象变得无法访问时,WeakReference被清除。但是在这种情况下,由于你无法使它可以访问,它将获得GC。)