Java工作面试。有多少对象符合垃圾回收条件?

标签 java reference garbage-collection

这是一个典型的 Java 求职面试问题。 System.gc(); 将收集多少对象?

我将在代码中使用以下名称:

  • a1 持有对 A1 的引用,
  • a2 持有对 A2 的引用,
  • mas 持有对 Mas 的引用,并且
  • list 持有对 List 的引用。

使用类。

package com.mock;

public class GCTest {

    static class A {

        private String myName;

        public A(String myName) {
            this.myName = myName;
        }
    }
}

用法。

package com.mock;

import com.mock.GCTest.A;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        A a1 = new A("a1"); // A ref to A1. 1 ref in all.
        A a2 = new A("a2"); // A ref to A2. 2 refs in all.
        ArrayList<A> list = new ArrayList<A>(); // A ref to the empty ArrayList. 3 refs in all.
        list.add(a1); // The list has a1 holding a ref to A1 
        A[] mas = new A[2]; // A ref to an array; it has nulls in it. 4 refs in all.
        mas[0] = a2; // Now mas holds the ref to A2.
        a2 = a1; // a2 holds the ref to A1 
        clear(mas); // Nothing changed because methods deals with copies of parameters rather than with parameters themselves. 
        a1 = null; // a1 no longer holds the ref to A1
        a2 = null; // a2 no longer holds the ref to A1
        System.gc(); // Nothing should be garbage collected
    }

    private static void clear(A[] mas) {
        mas = null;
    }

}

最佳答案

这很可能是一个棘手的问题。

System.gc() 的作用取决于底层垃圾收集器。

gc

public static void gc()

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

     Runtime.getRuntime().gc()


See Also:
    Runtime.gc()

你所知道的是:

  • 在 0 和“程序中的对象数”之间的 Object 将被垃圾收集。
  • 很有可能介于 0 和“应该被垃圾收集的对象数”之间。
  • 有一个相对较高的可能性,它会准确地收集“应该被垃圾收集的对象的数量”。

关于Java工作面试。有多少对象符合垃圾回收条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457137/

相关文章:

java - -Xms 和 -Xmx 之间的巨大差异的影响

.net - 设置字体真的有多重要?

java - 另一个 PHP JSONException : Value <br of type java. lang.String 无法转换为 JSONObject

java - 计算小数点后的数字,包括最后一个零

java - 在模拟中移动多辆车的有效方法

java - Android内存使用和对象引用

python - 重新链接 python 对象(即通过引用传递)

c# - VS 2010 : C# Project Cannot Open DLL

java - Java中的垃圾收集器是什么?

java - 如何将表格转为字符串?