gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:47:24 24 4
gpt4 key购买 nike

这是一个典型的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com