Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to object during finalize

Tags:

What happens if you save a reference to the current object during the finalize call? For example:

class foo {     ...     public void finalize() {         bar.REFERENCE = this;     } } 

Is the object garbage-collected, or not? What happens when you try to access bar.REFERENCE later?

like image 556
Nathaniel Flath Avatar asked Jun 16 '09 16:06

Nathaniel Flath


People also ask

In which condition is the object finalize () method?

finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Why finalize () method should be avoided?

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.

What is the role of finalize () in reference with garbage collection?

Finalize method in Java is an Object Class method that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the object from memory.

Can we stop finalize method getting called on object if yes how?

The finalize method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object. If an object never becomes unreachable, finalize() will never be called on it. If the GC doesn't run then finalize() may never be called.


1 Answers

The object is not garbage collected. This is know as "Object resurrection".

You must be careful with that, once the finalizer is called the gc won't call it again, on some enviroments like .NET you can re-register the finalizer but i'm not sure about java

like image 92
albertein Avatar answered Sep 30 '22 16:09

albertein