How far will the GC go

How far will Java GC go? Let's say I have this code:

public class MyClass {
    private Object myObject = new Object();
    public void clear() {
        myObject = null;
    }
}

public class MyMain {
    ...
    MyClass myClass = new MyClass();
    ...
    myClass.clear();
    myClass = null;
}

Do I need to call myClass.clear () before setting myClass to null to make sure GC will remove myObject inside myClass? Or is it enough to set myClass to null and GC will delete all nested objects?

Maybe I'm a little paranoid and the answer is as simple as "GC will ultimately delete any objects inaccessible to any running code or any future available code." So, if the created object is unavailable or will never be available in any running code, will it eventually become a victim of the GC, even if it is nested and makes the C ++ programmer scary?

+3
source share
9

, myClass.clear(). , . , , .

- . , , , ArrayList<T> null, , - , . , , myClass.clear(), .

. MyMain , ... , , myClass . , GC , , - , GC, - . .

+9

- , GC'd. .

Java ++.

+8

"" gc .

, :

    long[] arr = new long[7000000];
    //arr = null;
    arr = new long[7000000];

-Xmx100M, OutOfMemoryError. , arr null, . , arr , . , , . GC .

+7

, clear. GC myObject .

, GC , :

public class Foo
{
    public HashMap a;
    public HashMap b;

    public Foo() {
        a = new HashMap();
        b = new HashMap();
        a.put("b", b);
        b.put("a", a);
    }
}
// ...
public void someFunction() {
   Foo f = new Foo();
}

( a b , .)

f a b. f, f , GC , a b .

(- ) JLS.

+2

, . , ( " " " ", GC ). , GC.

, , finalize, , -, - , , - .

+1

GC . , . null.

, myObject.clear, myObject = null, reset null.

0

myclass null. , .

0

GC , . , , MyClass , myObject , , GC

0

myClass.clear(), myClass null, , GC myObject myClass?

clear myClass null.

, , , , myClass .

.

0
source

Source: https://habr.com/ru/post/1776292/


All Articles