将Java对象设置为null是否可以做任何事情? [英] Does setting Java objects to null do anything anymore?

查看:260
本文介绍了将Java对象设置为null是否可以做任何事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一些旧书,并找到Peter Hagger的一本Practical Java。在性能部分中,建议在不再需要时将对象引用设置为 null

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



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

解决方案


$ b $如果你有一个对象链A-> B-> C,那么一旦A不可达,A,B和C将全部有资格进行垃圾回收(假设没有别的指向B或C)。例如,没有必要也没有必要明确地将引用A-> B或B-> C设置为空。

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



曾经是 strong>将null引用设置的一些建议特别在长范围内,其中内存密集型对象在部分范围内不再使用。例如:

  {
BigObject obj = ...
doSomethingWith(obj);
obj = null; < - 显式设置为空
doSomethingElse();



$ b $ p
$ b

原因在于,因为 obj 仍然存在在范围内,那么在没有明确指定引用的情况下,直到 doSomethingElse()方法完成之后,它才会变为垃圾收集。这是可能不再适用于现代JVM的建议:事实证明,JIT编译器可以在不再使用给定本地对象引用的地方解决问题。


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.

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.

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.

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.

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();
}

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天全站免登陆