简体   繁体   English

Java中的匿名对象和垃圾收集

[英]Anonymous object and Garbage Collection in Java

My question is: When is an anonymous object swept by the garbage collector in Java? 我的问题是:什么时候Java中的垃圾收集器扫描了一个匿名对象?

The code is: 代码是:

class Test extends Thread
{
    Test(){}
    public void run()
    {
        for(int i=0;i<4;i++)
            System.out.println(this.getName()+"i="+i);
    }
    protected void finalize()
    {
        System.out.println("Finalized");
    }
    public static void main(String args[])
    {
        new Test().start();
    }
}

From what I know about Java, any unreferenced object is swept by the GC. 根据我对Java的了解,任何未引用的对象都会被GC扫描。 But there is no object reference here. 但这里没有对象参考。 Although the garbage collection process cannot be predetermined, but, still, when would the GC be "probably" done? 尽管无法预先确定垃圾收集过程,但是,GC何时“可能”完成?

An object is eligible for garbage collection when there are no references to it and any live thread is not accessing it. 当没有对它的引用并且任何活动线程没有访问它时,该对象有资格进行垃圾收集。 When to garbage collect it depends on JVM 何时进行垃圾收集取决于JVM

Actually garbage collection will remove any objects that not reachable from the stack (= all active function calls in all threads). 实际上,垃圾收集将删除任何无法从堆栈中访问的对象(=所有线程中的所有活动函数调用)。

When you call start() you are creating a new thread and java will call run() for you. 当你调用start()你正在创建一个新线程,java将为你调用run() In created this thread, the reference to your Test object is copied to the stack of the new thread. 在创建此线程时,对Test对象的引用将复制到新线程的堆栈中。 And by calling your run() is on the stack of the new thread. 通过调用run()是在新线程的堆栈上。

When your run() function is done, the thread will be removed. 完成run()函数后,线程将被删除。 And the Test object will be no longer referenced, and can be cleaned up. 并且将不再引用Test对象,并且可以清除它。 (in java you normally speak about eligible for cleanup , so you say: it is possible that it will be cleaned, but as always the garbage collection decides if/when it really happens. (在java中,你通常会说有eligible for cleanup ,所以你说:它可能会被清理,但一如既往垃圾收集决定它是否/何时真正发生。

Actually garbage collector will pick up objects when they are not accessible by any live threads. 实际上垃圾收集器会在任何活动线程无法访问它们时拾取对象。 So in your case object you created will be up for GC as soon as thread exits main method. 因此,在您的案例中,只要线程退出main方法,您创建的对象就会用于GC。

Imho the answer is still: It cannot be said. Imho答案仍然是:不能说。 However, in this case in can only be removed by the GC after the thread finished its work. 但是,在这种情况下,只有在线程完成其工作后才能通过GC删除。 The actual "finalization" time depends on some more factors. 实际的“最终确定”时间取决于更多因素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM