finalize() Flashcards
What is the purpose of the finalize method ?
Java allows objects to implement a method called finalize() that might get called. This
method gets called if the garbage collector tries to collect the object
Which characteristics of the finalize method you need to remember ?
If the garbage collector fails to collect the object
and tries to run it again later, the method doesn’t get called a second time.
Just keep in mind that it might not get called and that it definitely won’t be called twice.
Give a key attribute of static variables regarding scope and garbage collection !
The scope of static variables is limited to the class itself, meaning they can be accessed from anywhere within the class and can also be accessed by other classes using the class name.
In contrast, the scope of instance variables is limited to the specific object they belong to, meaning they can only be accessed through that particular instance. Thus, static variables are accessible from any context within the class, while instance variables are accessible only through the instance of the class.
while the static variable itself persists for the lifetime of the class, the object it references can be collected if it is no longer reachable.
KEY TAKEAWAY :
For an object referenced by a static variable to become eligible for garbage collection, the static reference must be reassigned to point to another object or set to null.
In contrast, an object referenced by an instance variable can become eligible for garbage collection when that instance variable goes out of scope, meaning there are no remaining references to that object. Thus, static references have a more persistent lifecycle compared to instance variables.
Give a practice that you should avoid at all cost !
public class Finalizer {
private static List objects = new ArrayList();
protected void finalize() { objects.add(this); // Don't do this } }
The finalize method can be called under the following scenario:
- Instance Creation: If an instance of the Finalizer class is created and later becomes unreachable (i.e., there are no more references to that instance), the garbage collector may call the finalize method on that instance before it reclaims its memory.
EXAMPLE SCENARIO :
public class Test {
public static void main(String[] args) {
Finalizer obj = new Finalizer();
obj = null; // The instance becomes unreachable
System.gc(); // Suggest garbage collection
}
}
In this example:
The instance obj of Finalizer becomes unreachable when it is set to null.
When the garbage collector runs (triggered by System.gc()), it may call the finalize method on the instance before it is collected.
The finalize method would then add the instance to the static objects list.