这里有一个典型的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;
}
}发布于 2013-12-10 06:15:48
我的答案是0,因为list和mas的元素都包含对A1 (list)和A2 (mas)的引用。
为了简化我的答案,我创建了三个图表。矩形对应于内存中的块;圆圈对应于对象。灰色箭头对应于不再存在的引用。
先于a1 = a2.

后a1 = a2.

a1和a2都不保存引用

我可以为类finilize()重写A,以查看是否符合要求的。
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
System.out.println("finalize: " + myName);
super.finalize();
}虽然我在测试代码时看到了日志,但no 100%保证在调用System.gc()后内存是透明的。
运行垃圾收集器。 调用gc方法建议Java虚拟机将精力用于回收未使用的对象,以便使它们当前占用的内存可用于快速重用。当控件从方法调用返回时,Java虚拟机已尽最大努力从所有丢弃的对象中回收空间。
发布于 2013-12-08 19:20:16
这很可能是刁钻的问题。
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()你所知道的是:
Object将被垃圾收集。https://stackoverflow.com/questions/20457137
复制相似问题