有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

静态arraylist中对象的Java垃圾arraylist字段

请看这个:

class MyUtility{

public static MyStock stock;

}

class MyStock{

public ArrayList<SomeThing> myListOfThings;

}


class SomeThing{

public ArrayList<WhatEver> myWhatever;
public double [] myArray;

}

因此,我可以随时随地访问我的实用程序。库存(线程安全不是问题)

我知道GC不会清理“myListOfThings”,我也不在乎:这个列表是全局的和静态的,这是有充分理由的

但是GC会清除“MyWhatch”吗?如果没有,如何强制/让其省略

我的意思是:如果在一个“某物”的生命周期中,“myWhatever”数组列表大小变为123,那么是0,或者myArray从新的double[123]变为null


共 (2) 个答案

  1. # 1 楼答案

    你不能强迫GC运行

    Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

    In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector. https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

    如果您希望GC能够清除内存,请使用“myWhatever” 然后你需要或清除列表:这样列表中的任何对象(但在其他部分中没有引用)都将被清除或使列表为空,这将产生相同的效果

    myWhatever.clear();
    

    或者

    myWhatever = null;
    

    在第一种情况下,您仍将拥有对空列表的引用,因此不必重新创建它,在第二种情况下,您还将标记对符合GC条件的列表的引用

  2. # 2 楼答案

    系统。gc()让JVM知道您想要进行垃圾收集,但并不保证会发生

    当没有更多指向对象的引用时,可以对其进行垃圾收集