Skip to main content
OCA Java Programmer 1Z0-803

JAVA Object Lifecycle, de-referencing and garbage collection

By November 10, 2013September 12th, 2022No Comments

We all know what it is like waiting for our bins to be emptied and we know we have to be nice to the garbage collectors. We Java is the same, if you are nice to the garbage collector Java will be nice to you. So in the aim of keeping the refuse engineers happy we will see how memory is used and released in Jave 7 SE. Once a reference is made to an Object that reference variable will exist and consume memory until the JVM garbage collector releases the memory. The garbage collector will release memory on object references that have been cleared. This may be done explicitly or as the object falls out of scope.

Create an object reference

The start of the life-cycle is when we instantiate the object. For example:

ObjectLife of = new ObjectLife();

The above code creates a reference variable of that is an instance of the object class ObjectLife, in the case. The variable of will consume memory while it is still referenced. As developers we can but do not have to explicitly de-reference objects. When the variable becomes is not longer in scope it is de-referenced automatically. This will normally be at the end of the code block that the variable was instantiated within.

Explicitly de-reference variables

If we have longer running code then it may be beneficial to explicitly de-reference variables when they are no longer needed. This can  be done using code similar to the following:

of = null;

This does not release the memory but the references to the object variable have now been cleared and the garbage-collector will release the memory when it next runs.

Garbage Collector

The garbage collector is part of the JVM, java virtual machine, and will return memory that is no longer used by variables back to the heap. It runs as a background process and under most circumstances this can be left to manage itself. The GC process is complex but generally works well self-managed.