user1682132
user1682132

Reputation: 61

overriding finalize(), referencing object inside it

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?

Upvotes: 1

Views: 69

Answers (3)

user207421
user207421

Reputation: 311052

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.

Upvotes: 1

Scott Sosna
Scott Sosna

Reputation: 1413

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.

Upvotes: 0

Daedric
Daedric

Reputation: 500

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.

Upvotes: 0

Related Questions