在方法调用期间创建的本地Java对象的生命周期 [英] Life cycle of local Java objects created during a method call

查看:102
本文介绍了在方法调用期间创建的本地Java对象的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方法调用中,如果在该调用期间创建对象。这些垃圾何时被垃圾收集?

它们是否放置在堆上,然后与堆中的其他对象一起收集垃圾。或者他们是否先垃圾收集,因为他们不需要。

解决方案

在方法范围内创建的对象在方法关闭时有资格进行垃圾回收 - 除非该引用作为返回值传回。在这种情况下,调用者可能会或可能不会挂在该引用上并阻止其被引用。

由于垃圾收集器根据自己的指示灯在其自己的线程上运行,因此您不一定知道何时清理对象或是否在别处分配了对象也符合资格。


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.

解决方案

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对象的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆