This below discussion is not exactly about
creating java objects but good practices after you create java object.
Eliminate obsolete object references
We know that in java, objects are
automatically garbage collected, so we don’t give much attention on how objects
are getting destroyed. But sometimes memory
leak can happen. The reason behind this
as the stack grows and then shrinks, the objects that were popped out from the
stack will not be garbage collected even if the program using the stack has no
more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is a reference that
will never be dereferenced again.
For e.g.
public Object pop() {
if(size == 0) {
throw new
EmptyStackException();
}
return result =
elements[--size];
}
In this case, any references outside of the “active
portion” of the element array are obsolete.
The active portion consists of the elements whose index is less than size.
In order to solve this memory leak, we can
nullify the object.
public Object pop() {
if(size == 0) {
throw new EmptyStackException();
}
object result = elements[--size];
element[size] = null;
return result;
}
But it should be noticed that nullifying an
object reference should be exception rather than the norm. The best way to eliminate an obsolete
reference is to let the variable that contained the reference fall out of
scope. This occurs automatically if each
variable is defined in the narrowest possible scope.
Another source of memory leaks is caches. We may put an object reference in cache and
forget it. There may be many solutions for this. One can be making the cache as WeakHashMap so that entries will be
removed automatically after they become obsolete.
One more common source of memory leaks is
listeners and other callbacks. Again the better way to keep safe in this
situation is to keep weak reference by storing them only as keys in a WeakHasMap.
{Courtesy: Effective Java - Joshua Bloch}
{Courtesy: Effective Java - Joshua Bloch}