search

Home  >  Q&A  >  body text

java - 关于System.gc()的执行?

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中文网2889 days ago275

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:59:13

    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

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:59:13

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

    reply
    0
  • 黄舟

    黄舟2017-04-17 17:59:13

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 17:59:13

    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.

    reply
    0
  • Cancelreply