Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 556
someone Avatar asked Dec 27 '12 17:12

someone


1 Answers

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.

like image 146
Sergey Kalinichenko Avatar answered Oct 25 '22 23:10

Sergey Kalinichenko