简体   繁体   中英

Objects Good Practice

I want to write applications that don't leak, so I am looking for best practice to avoid this.

I always close my resultSets and Connections. But I usually don't nullify my objects when finished with them and leave them to GC to clean up.

Is this bad practice? should I be nullifying my ArrayLists and Interators when I am done with them?

Also is there other ways to deal with objects to keep memory intact?

You do not need to nullify local variables when you are done with them: Java compiler is smart enough to figure out when to discard the object.

Class member variables, on the other hand, need to be considered differently: if a collection holds objects inside another object, it may make sense to clear out the collection once you are done with it. This is important only when the lifetime of the outer object is significantly longer than the lifetime of the objects inside its collections. Otherwise, garbage collector will deal with collecting the objects without any help from your code.

I suggest to read Effective Java Item 6 "Eliminate obsolete object references". It discusses many aspects of the problem. But the basic rule is Nulling out object references should be the exception rather than the norm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM