java - 关于System.gc()的执行?
PHP中文网
PHP中文网 2017-04-17 17:57:13
0
4
268
package FinalizeTest;

public class Person {
    
    public Person(){
        System.out.println("person created");
    }

    @Override
    protected void finalize() throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("gc ");
        throw new Exception("no effect");
    }
}



package FinalizeTest;

public class MainTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person per = new Person();
        per = null;
        System.gc();
        System.out.println("hello world");

    }

}

输出为

person created
hello world
gc 

代码如上所示, 求解释为什么hello world会在gc之前输出??

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
洪涛

About java finalize() Don’t be confused with c/c++, java programmers can never decide the timing of garbage collection.
Official description:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

finalize()It only defines the action during recycling, but the specific time to collect is still determined by the garbage collector itself.

Read the javadoc carefully

迷茫

System.gc(); just tells gc to perform a recycling action, but what to recycle is still decided by gc itself

黄舟

The function of System.gc() is only to remind the virtual machine to perform garbage collection. It is up to the virtual machine to decide whether to recycle or not.

You can understand that this action is asynchronous.

左手右手慢动作

To put it simply, although you actively called System.gc(); whether it will be recycled and when it will be recycled is decided by the garbage collector itself. It has no direct relationship with you. You execute your code, and it Perform its garbage collection.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template