java 在处理后将对象设置为 null 是一个好习惯吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14058834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:55:33  来源:igfitidea点击:

Is it a good practice to set an object to null after processing?

javagarbage-collection

提问by someone

I have scenario like this:

我有这样的场景:

public void processData(String name,String value) {

/* line 1 */    MyDTO dto = new MyDTO();  
/* line 2 */    dto.setName(name);
/* line 3 */    dto.setValue(value);
/* line 4 */    sendThroughJMSChannel(dto);
/* line 5 */    dto = null; //As a best practice, should I do this ?

}

In my program after line 4I don't require dtofor further processing. As a best practice, should I set dtoto nullas in line 5or ignore it?

第 4 行之后的程序中,我不需要dto进一步处理。作为最佳实践,我应该设置dtonull第5行,或者忽略它?

By setting it to null, I'm expecting fast garbage collection. Is it correct?

通过将其设置为null,我期待快速垃圾收集。这是正确的吗?

回答by dasblinkenlight

No, do not set local variables to nullto hasten their collection by the GC: the compiler is smart enough to figure it out without your help; the nullassignments will only make your code look dirty.

不,不要将局部变量设置为null以加快 GC 收集它们的速度:编译器足够聪明,无需您的帮助即可解决;该null任务只会让你的代码看起来很脏。

Non-locals are a different story: if you have a member variable that might stay around for longer than necessary, it is a good idea to set it to nulland prevent lingerer memory leaks.

非本地变量是另一回事:如果您有一个成员变量可能会停留超过必要的时间,最好将其设置为null并防止lingerer memory leaks

回答by Jigar Joshi

It will be out of scope it self after line 4 (once method invocation is over) so not required in this case

在第 4 行之后(一旦方法调用结束),它将超出其自身的范围,因此在这种情况下不需要

回答by Narita

As already been said, compiler is smart enough for the local scope but again in the non local scope it is a lot more context specific. One needs to understand how legitimate it is to nullify the reference at a particular point. Say when using a HashMap -

正如已经说过的,编译器对于本地范围足够聪明,但同样在非本地范围内,它是更多的上下文特定的。人们需要了解在特定点取消引用的合法性。使用 HashMap 时说 -

Map<String, Object> entry = new HashMap<String, Object>();
String name = "test";             
Object o = new Object();          
entry.put(name, o);                

o = null; 
name = null; 

System.gc(); // Nothing is eligible !!! Still referenced by the Map.

Object test = entry.get("test");    // Returns the object.

The entry must be removed from being referenced from the HashMap first, in this scenario.

在这种情况下,必须首先从 HashMap 中删除条目。

回答by Risin

it is good practice if you are planning to code in C or C++ in the future.

如果您打算将来使用 C 或 C++ 进行编码,这是一种很好的做法。