Garbage collection is a daemon thread. Clear up the unreachable objects on the heap.
Daemon Thread
Java offers two types of threads: user threads and daemon threads.
User threads are high-priority threads.The JVM will wait for any user thread to complete its task before terminating it.
On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads. JVM can exit if only daemon threads are running, no other user threads.
Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache.
Unreachable Objects
Object one = new Object();//a
Object two = new Object();//b
one = two;//a is not referenced anymore, b is referenced by two pointers
one = null;
two = null;//b is not referenced anymore
Garbage collection Cannot be forced to run.
System.gc()
call to suggest JVM to run the garbage collection: JVM might or might not call the garbage collector thread.
JVM's garbage collector thread is only run when the JVM thinks that it is running out of memory because JVM doesn't want to waste the system resource if there are no object to be cleaned up.
We don't usually rely on the finalize method to clean up our resources. We typically use our own methods.
object.finalize()
- every class inherits the
finalize()
method from java.lang.Object - the method is called by the garbage collector when it determines no more references to the object exist
- the Object finalize method performs no actions but it may be overridden by any class
- normally it should be overridden to clean-up non-Java resources ie closing a file (actually what to do just before it is garbage collected)
if overridding
finalize()
it is good programming practice to use a try-catch-finally statement and to always callsuper.finalize()
. This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling classprotected void finalize() throws Throwable { try { close(); // close open files } finally { super.finalize(); } }
Wherever we use the resources, that is where we close the resources. For example, if you open a database connection or IO streams, we close them inside the method itself.