将 Java 对象设置为 null 有什么作用吗? [英] Does setting Java objects to null do anything anymore?

查看:26
本文介绍了将 Java 对象设置为 null 有什么作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在浏览一些旧书时发现了一份 Peter Hagger 的实用 Java".在性能部分,建议在不再需要时将对象引用设置为 null.

I was browsing some old books and found a copy of "Practical Java" by Peter Hagger. In the performance section, there is a recommendation to set object references to null when no longer needed.

在 Java 中,将对象引用设置为 null 是否会提高性能或垃圾收集效率?如果是这样,在什么情况下这是一个问题?容器类?对象组成?匿名内部类?

In Java, does setting object references to null improve performance or garbage collection efficiency? If so, in what cases is this an issue? Container classes? Object composition? Anonymous inner classes?

我经常在代码中看到这一点.这是现在已经过时的编程建议还是仍然有用?

I see this in code pretty often. Is this now obsolete programming advice or is it still useful?

推荐答案

这取决于您何时考虑将引用归零.

It depends a bit on when you were thinking of nulling the reference.

如果您有一个对象链 A->B->C,那么一旦 A 不可访问,A、B 和 C 都将有资格进行垃圾收集(假设没有其他内容指的是 B 或 C).例如,没有必要,也从来没有必要,将引用 A->B 或 B->C 显式设置为 null.

If you have an object chain A->B->C, then once A is not reachable, A, B and C will all be eligible for garbage collection (assuming nothing else is referring to either B or C). There's no need, and never has been any need, to explicitly set references A->B or B->C to null, for example.

除此之外,大多数时候问题并没有真正出现,因为实际上您正在处理集合中的对象.您通常应该始终考虑通过调用适当的 remove() 方法从列表、地图等中删除对象.

Apart from that, most of the time the issue doesn't really arise, because in reality you're dealing with objects in collections. You should generally always be thinking of removing objects from lists, maps etc by calling the appropiate remove() method.

过去一些建议将引用设置为 null 的情况特别是在一个长作用域中,在该作用域中途停止使用内存密集型对象.例如:

The case where there used to be some advice to set references to null was specifically in a long scope where a memory-intensive object ceased to be used partway through the scope. For example:

{
  BigObject obj = ...
  doSomethingWith(obj);
  obj = null;             <-- explicitly set to null
  doSomethingElse();
}

这里的基本原理是,因为 obj 仍在作用域内,所以如果没有显式地将引用清空,它在 doSomethingElse() 之前不会成为垃圾收集器方法完成.这是现代 JVM 可能不再适用的建议:事实证明,JIT 编译器可以确定在什么时候不再使用给定的本地对象引用.

The rationale here was that because obj is still in scope, then without the explicit nulling of the reference, it does not become garbage collectable until after the doSomethingElse() method completes. And this is the advice that probably no longer holds on modern JVMs: it turns out that the JIT compiler can work out at what point a given local object reference is no longer used.

这篇关于将 Java 对象设置为 null 有什么作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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