简体   繁体   English

Java 中的对象销毁

[英]Object Destruction in Java

From the below example, In Case 1 the object is created in Class level and in Case 2 its created in Method level.从下面的示例中,在案例 1 中,对象是在类级别创建的,在案例 2 中,它是在方法级别创建的。

My understanding that in Case 2 once the method completes its execution the object is removed from heap memory .我的理解是,在案例 2 中,一旦方法完成执行,对象就会从堆内存中删除。 Is my understanding correct ?我的理解正确吗?

Now My question is,in both the cases when will the object be removed from the Heap memory and which is efficient way of using in different context ?现在我的问题是,在这两种情况下,何时将对象从堆内存中删除,哪种是在不同上下文中使用的有效方式?

public class A()
    {
        ClassB obj = new ClassB(); // Case 1
        private void method()
        {
            ClassB obj = new ClassB(); // Case 2
        }

    }

Might depend on your Java VM implementation, but generally GC is run only after the heap is filled / saturated.可能取决于您的 Java VM 实现,但通常 GC 仅在堆填充/饱和后运行。 So no, most probably it won't be removed immediately.所以不,很可能它不会立即被删除。

In Your program.在你的程序中。 you have written only one line in which only declaration and initialization done.你只写了一行,其中只完成了声明和初始化。 and one more thing i want to ask that is it class , Method or constructor .还有一件事我想问的是它是classMethod还是constructor

private example(){ //what is example ?? Is it class or method or constructor ?
      ClassA obj = new ClassA();
    }

but i want to tell you ClassA obj will be eligible for gc after the } (Closing Paranthesis) execution done.但我想告诉你ClassA obj} (闭括号)执行完成后将有资格进行 gc。 but it is totally depends upon the jvm that when gc will be executed then collect and destroy the object.但这完全取决于 jvm 何时执行 gc 然后收集和销毁对象。

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

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