首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java求职面试。有多少对象符合垃圾收集的条件?

Java求职面试。有多少对象符合垃圾收集的条件?
EN

Stack Overflow用户
提问于 2013-12-08 18:22:00
回答 2查看 1.2K关注 0票数 3

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

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

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

使用了.

代码语言:javascript
复制
package com.mock;

public class GCTest {

    static class A {

        private String myName;

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

使用.

代码语言:javascript
复制
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;
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-10 06:15:48

我的答案是0,因为listmas的元素都包含对A1 (list)和A2 (mas)的引用。

为了简化我的答案,我创建了三个图表。矩形对应于内存中的块;圆圈对应于对象。灰色箭头对应于不再存在的引用。

先于a1 = a2.

后a1 = a2.

a1和a2都不保存引用

我可以为类finilize()重写A,以查看是否符合要求的

代码语言:javascript
复制
@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虚拟机已尽最大努力从所有丢弃的对象中回收空间。

票数 3
EN

Stack Overflow用户

发布于 2013-12-08 19:20:16

这很可能是刁钻的问题。

System.gc()所做的工作依赖于底层的垃圾收集器。

代码语言:javascript
复制
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和“应该垃圾收集的对象的数量”之间。
  • 有一个相对较高的相似之处,即它将垃圾收集,确切地说是“应该被垃圾收集的对象数量”。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20457137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档