What happens if I override finalize() and give reference to an object. Will that object ever be garbage collected? What is the other way to clean that object from the memory?
-
1Don't do that. Presumably it would create a memory leak. What problem are you trying to solve? – Elliott Frisch Apr 26 '15 at 02:49
-
http://stackoverflow.com/questions/17372533/why-we-override-finalize-method-in-java Please check this. – Mohan Raj Apr 26 '15 at 02:59
-
What are you trying to achieve? – Apr 26 '15 at 03:53
3 Answers
From the Javadoc:
The finalize method may take any action, including making this object available again to other threads.
However:
The finalize method is never invoked more than once by a Java virtual machine for any given object.

- 305,947
- 44
- 307
- 483
Finalize() is designed to be called by the garbage collector to remove de-referenced objects, if an object is re-referenced before Finalize() is called then you have simple prevented the GC from destroying it as it now has references again it is safe, that is assuming it was not taken during the period it was de-referenced, which could cause problems.

- 502
- 4
- 23
Remember that finalize is only called once by the JVM, so subsequence GCs will just run without giving another chance to reassign references, save objects, whatever. Potentially could cause a memory leak.

- 1,443
- 1
- 8
- 8