Reputation: 6572
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 4 I don't require dto
for further processing. As a best practice, should I set dto
to null
as in line 5 or ignore it?
By setting it to null
, I'm expecting fast garbage collection. Is it correct?
Upvotes: 15
Views: 12553
Reputation: 429
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 -
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.
Upvotes: 0
Reputation: 726509
No, do not set local variables to null
to hasten their collection by the GC: the compiler is smart enough to figure it out without your help; the null
assignments will only make your code look dirty.
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 null
and prevent lingerer memory leaks.
Upvotes: 31
Reputation: 240880
It will be out of scope it self after line 4 (once method invocation is over) so not required in this case
Upvotes: 13