显式归零 [英] Explicit nulling

查看:116
本文介绍了显式归零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中什么情况下显式nulling有用。它是否以任何方式通过使对象无法访问或某种东西来帮助垃圾收集器?它被认为是一个好习惯吗?

In what situations in java is explicit nulling useful. Does it in any way assist the garbage collector by making objects unreachable or something? Is it considered to be a good practice?

推荐答案

在Java中,如果你有可以帮助得到了一个非常长时间运行的方法,对对象的唯一引用是通过局部变量。当你不再需要它时,将该局部变量设置为null(但是当该方法将继续运行很长时间时)可以帮助GC。 (在C#中,这很少有用,因为GC会考虑最后可能的使用。这种优化可能会让它在Java中出现一段时间 - 我不知道。)

In Java it can help if you've got a very long-running method, and the only reference to the an object is via a local variable. Setting that local variable to null when you don't need it any more (but when the method is going to continue to run for a long time) can help the GC. (In C# this is very rarely useful as the GC takes "last possible use" into account. That optimization may make it to Java some time - I don't know.)

同样,如果你有一个成员字段引用一个对象而你不再需要它,你可以通过将该字段设置为null来帮助GC。

Likewise if you've got a member field referring to an object and you no longer need it, you could potentially aid GC by setting the field to null.

In然而,根据我的经验,很少实际上对这些事情都很有用,而且会使代码变得更加混乱。很少有方法真正运行很长时间,将变量设置为null实际上与您希望方法实现的内容无关。当你不需要的时候这样做是不好的做法,如果你需要,你应该看看重构是否可以改善你的设计。 (你的方法或类型可能做得太多了。)

In my experience, however, it's rarely actually useful to do either of these things, and it makes the code messier. Very few methods really run for a long time, and setting a variable to null really has nothing to do with what you want the method to achieve. It's not good practice to do it when you don't need to, and if you do need to you should see whether refactoring could improve your design in the first place. (It's possible that your method or type is doing too much.)

注意,将变量设置为null完全是被动的 - 它不会通知垃圾收集器可以收集对象,它只是避免垃圾收集器将该引用视为下次(GC)运行时保持对象存活的理由。

Note that setting the variable to null is entirely passive - it doesn't inform the garbage collector that the object can be collected, it just avoids the garbage collector seeing that reference as a reason to keep the object alive next time it (the GC) runs.

这篇关于显式归零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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