Sunday 7 August 2011

Obsolete Object References




Unlike C and C++ ,Java takes care of memory management through Garbage-collector,but  care must be taken to avoid the unintentional objects (Obsolete Object References ) occurring.An obsolete reference is a reference that will never be dereferred again.

refer the following sample code of  Stack.

































When the pop is called the copy of the reference is poped out ,but there will be unintentional reference still lying in the array  and it will be replaced for the push of a new item.


But,if there are series of pop outs and no new elements pushed there it results in many obsolete references.This can be avoided by nulling out the references after each pop as below.













Eliminating this unintentional references results in  Better performance, less memory, and When nulling out the references, if they get de-referred to later by a mistake, you will get a NullPointerException (as you should!)

Its always beneficial to detect programming errors as quickly as possible.

(Inspired from Effective Java Item:5)


Cheers. . . .  ;-)

2 comments: