您是否需要清空对象? [英] do you need to null objects?

查看:127
本文介绍了您是否需要清空对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复-如何销毁Java对象?

我的问题很简单.我是使用Java开发应用程序的新手,不确定在完成对象后是否需要将对象清空.例如,我正在使用libGDX来创建游戏,并且正在创建多个对象(演员).当我完成他们的工作后,我只需致电

My question is very simple. I am new to app development with Java and am not sure whether I need to null objects after i am finished with them. for example i am using libGDX to create a game and I have several objects (Actors) being created. when I am finished with them do I simply call

obj.remove();

还是我-

obj.remove();
obj = null;

我是通过清空对象来节省内存还是没有优势?

do I save memory by nulling objects or is there no advantage to be had?

推荐答案

通常,在Java中,将对象引用标记为null是为了使它明确地可用于GC.如果对象不可访问,那么它就有资格使用GC,是的,您可以将其标记为null并让GC进行工作.

Generally, in java, marking the Object references as null is done to make it explicitly eligible for GC. If an object is unreachable, then it becomes eligible for GC, so, yes, you can mark it as null and let the GC do its work.

仅当没有引用指向该对象时,该对象才会变为不可访问.

The Object will become unreachable only when there is no reference pointing to it.

示例:

class MyTest {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("object is unreachable..");
    }
}
// In some other class
public static void main(String[] args) {
        MyTest o1 = new MyTest();
        MyTest o2 = new MyTest();
        System.gc();
        o1 = null;
        System.gc();
        System.out.println("hello");
}
O/P:
hello
object is unreachable..

在这里,"hello"之后可能有几千行代码.您可能希望通过将对象的引用标记为null来简化GC的工作.

Here, you might have several thousand lines of code after "hello". You might want to make the GC's job easier by marking the object's references as null.

这篇关于您是否需要清空对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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