问题描述
在方法调用中,如果我在该调用期间创建了一个对象.这些对象何时被垃圾收集?
In a method call, if I create an object during that call. When are those objects garbage collected?
它们是否放置在堆上,然后与堆上的其他对象一起收集垃圾.还是因为不需要它们而较早地收集了垃圾.该方法的执行已完成.
Are they placed on the heap and then garbage collected along with other objects on the heap. Or are they garbage collected earlier because they are not needed. The execution of that method has completed.
推荐答案
当方法关闭时,在方法范围内创建的对象有资格进行垃圾回收 - 除非该引用作为返回值传回.在这种情况下,调用者可能会或可能不会挂在该引用上并阻止它被 gc'd.
Objects created within method scope are eligible for garbage collection when the method is closed - unless that reference is passed back as the return value. In that case, the caller may or may not hang onto that reference and prevent it from being gc'd.
由于垃圾收集器根据自己的灯在自己的线程上运行,因此您不一定知道对象何时被清理,或者分配在其他地方的对象是否也符合条件.
Since the garbage collector runs on its own thread according to its own lights, you don't necessarily know when an object is cleaned up, or whether or not objects allocated elsewhere are eligible as well.
这篇关于方法调用期间创建的本地 Java 对象的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!