What is the garbage collector in Java?

前端 未结 16 1186
故里飘歌
故里飘歌 2020-11-22 11:24

I am new to Java and confused about the garbage collector in Java. What does it actually do and when does it comes into action. Please describe some of the properties of the

16条回答
  •  轮回少年
    2020-11-22 12:04

    It frees memory allocated to objects that are not being used by the program any more - hence the name "garbage". For example:

    public static Object otherMethod(Object obj) {
        return new Object();
    }
    
    public static void main(String[] args) {
        Object myObj = new Object();
        myObj = otherMethod(myObj);
        // ... more code ...  
    }
    

    I know this is extremely contrived, but here after you call otherMethod() the original Object created is made unreachable - and that's "garbage" that gets garbage collected.

    In Java the GC runs automatically, but you can also call it explicitly with System.gc() and try to force a major garbage collection. As Pascal Thivent points out, you really shouldn't have to do this and it might do more harm than good (see this question).

    For more, see the wikipedia entry on Garbage collection and Tuning Garbage Collection (from Oracle)

提交回复
热议问题