What is difference between System.gc() and finalize() method in java?

sayali picture sayali · Apr 17, 2012 · Viewed 22.6k times · Source

I am confuse in between system.gc() and finalize() method of java. We can't force to collect garbage object to JVM. We are allow to write both methods in our java code then if both are used for garbage collection, then what is point in providing two methods for garbage collection by java?

Please tell me the exact working of both methods and internally how it works?

Answer

ewernli picture ewernli · Apr 17, 2012

System.gc() kindly asks the sytem to perform a garbage collection. Javadoc says:

Runs the garbage collector.

You can not control how "hard" the garbage collector will work. How the garbage collector work internally is VM-specific and a research topic on its own. But there are usually "full" garbage collection and some smaller "incremental" collection going on. So consider System.gc as a request, but there's not guaranteed that garbage collection of your object will happen.

Object.finalize() can be overriden to specify what to do when a given object is garbage collected (actually what to do just before it is garbage collected). Javadoc says:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Classical use of finalizer are to de-allocate system resources when an object is garbage collected, e.g. release file handles, temporary files, etc.

Do not use finalizer to perform actions when the JVM exits. For this purpose use a shutdown hook that you register with Runtime.getRuntime().addShutdownHook(Thread).