I read about the method finalize(),that is call by the garbage collector before to free memory. From documentation,finalize is used to make cleanup activities. But what "things" are cleanup in this "cleanup activities"
-
all the un-referenced objects – AnkeyNigam Jul 26 '15 at 11:56
-
1Check these links: http://stackoverflow.com/questions/2506488/when-is-the-finalize-method-called-in-java and http://javarevisited.blogspot.in/2012/03/finalize-method-in-java-tutorial.html – Somnath Musib Jul 26 '15 at 11:57
2 Answers
A typical type of cleanup is releasing any system resources the instance has allocated, such as file descriptors in the case of a FileInputStream
.
Note that a good Java program will never rely on the cleanup performed in the object's finalizer and will instead explicitly ask the object to release the resources when its use expires.
There are unfortunately some ugly examples in the JDK where the finalizer is the only mechanism provided. A notorious one is the DirectByteBuffer
, which allocates native (off-heap) memory and provides no public method to free it.

- 195,646
- 29
- 319
- 436
From the Bruce Eckel's "Thinking in Java" book:
It would seem that finalize( ) is in place because of the possibility that you’ll do something Clike by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions might be called to allocate storage, and unless you call free( ), that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to call it in a native method inside your finalize( ).
After reading this, you probably get the idea that you won’t use finalize( ) much.

- 1,380
- 1
- 16
- 23