finalize method is called on an object by garbage collector. finalize method is called only once by garbage collector for an object.
Contents of page >
- 13 salient features of finalize method in java >
- Finalize method is defined in which class in java
- Why finalize is protected method in java?
- Who calls finalize method in java?
- When garbage collector calls finalize method in java?
- Can finalize method make object again available in java ?
- Perform clean actions in java
- Java code in finalize method in java
- Which thread invokes finalize method in java?
- What if Exception is thrown in finalize method in java?
- How to call finalize method explicitly in java?
- We can force early garbage collection in java
- finalize methods are not chained like constructors in java
- When not to override finalize method of class in java
13 salient features of finalize method in java >
- Finalize method is defined in which class - finalize() method is defined in java.lang.Object. So finalize method is inherited in all the classes, because all the classes inherit Object class by default in java.
Signature of finalize method in java is >
protected void finalize() throws Throwable { }
|
protected > It is protected method. (We will discuss
later in post
why finalize method is protected)
void > Method does not return anything.
- Why finalize is protected method in java?
Definition of protected method is - The subclass can use protected method only through inheritance in java.
finalize method for object can’t be called from some other class outside the package without inheritance.
finalize method is protected because class itself or any of its subClass is only allowed to invoke finalize method in java.
- Who calls finalize method in java?
finalize method is called on an object by garbage collector. finalize method is called only once by garbage collector for an object.
- When garbage collector calls finalize method in java?
When there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
finalize method is called when JVM determines that no live thread can access the object in java.
- Can finalize method make object again available in java ?
The finalize method may make an object available again to other threads.
If object is made available in finally method by some thread, will finalize method be called again by garbage collector in java?
No, finalize method won’t be called again by thread, though it may be called explicitly.
- Perform clean actions - General purpose of finalize is to perform cleanup actions before the object is permanently discarded in java.
For an example - the finalize method for some input/output connection might perform some I/O transactions to break the connection before the object is permanently discarded.
- Java code in finalize method - The finalize method does not have any code. It is just called by garbage collector before discarding object. So, subclasses of Object can override the method in java.
- Which thread invokes finalize method in java?
Daemon threads are low priority threads which runs intermittently in background for doing garbage collection.
- thread calling finalize method does not hold any locks in java - It is guaranteed that thread that invokes finalize will not be holding any user-visible synchronization locks at invocation of finalize method.
- What if Exception is thrown in finalize method in java?
- exception is ignored,
- thread is terminated and
- object is discarded.
Note : Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.
You must be thinking why exception is ignored in java?
When Exception occurs in finally method it is ignored because JVM itself executes the finalize method via garbage collector. So there is no scope of propagating exception further i.e. beyond JVM, hence exception is ignored.
- How to call finalize method explicitly in java?
Though finalize method is called by garbage collector but we may call the method explicitly in java.
Now we will write a program/ example to override finalize method of java.lang.Object and call it explicitly in java >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class FinalizeTest {
@Override
protected void finalize() throws Throwable {
try {
System.out.println("in finalize() method, "
+ "doing cleanup activity");
} catch (Throwable throwable) {
throw throwable;
}
}
public static void main(String[] args) {
FinalizeTest obj = new FinalizeTest();
System.out.println("in main() method");
try {
obj.finalize(); //call finalize() method explicitly
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
/*OUTPUT
in main() method
in finalize() method, doing cleanup activity
*/
|
- We can force early garbage collection in java by using following methods >
System.gc();
Runtime.getRuntime().gc();
System.runFinalization();
Runtime.getRuntime().runFinalization();
By calling these methods JVM runs the finalize() methods of any objects pending finalization i.e. objects which have been discarded but there finalize method is yet to be run. After finalize method is executed JVM reclaims space from all the discarded objects.
Note : Calling these methods does not guarantee that it will immediately start performing garbage collection.
When any of these methods is called daemon threads which are low priority threads which runs intermittently in background are given high priority to perform garbage collection.
Must know :
System.gc() internally calls Runtime.getRuntime().gc()
|
and
System.runFinalization() internally calls Runtime.getRuntime().runFinalization()
|
- finalize methods are not chained like constructors in java, because if overridden finalize method of subclass does not invoke finalize method of its superclass explicitly than superclass’s finalize() method will never be invoked.
Program to show overridden finalize method of subclass must invoke finalize method of its superclass explicitly (by calling super.finalize();) in finally block.
class SuperClass {
@Override
protected void finalize() throws Throwable {
try {
System.out.println("in finalize() method of SuperClass, "
+ "doing cleanup activity SuperClass");
} catch (Throwable throwable) {
throw throwable;
}
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class Subclass extends SuperClass{
@Override
protected void finalize() throws Throwable {
try {
System.out.println("in finalize() method of Subclass, "
+ "doing cleanup activity of Subclass");
}catch (Throwable throwable) {
throw throwable;
}finally{
super.finalize();
}
}
public static void main(String[] args) {
Subclass subclass = new Subclass();
System.out.println("in main() method");
try {
subclass.finalize(); //call finalize() method explicitly
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
/*OUTPUT
in main() method
in finalize() method of Subclass, doing cleanup activity of Subclass
in finalize() method of SuperClass, doing cleanup activity SuperClass
*/
|
Try executing above program by commenting super.finalize() and you will see that superclass’s finalize() method will never be invoked in java.
When to override finalize method of class in java>
- Closing file input stream in finalize method is good idea because when there are no references left to it we must call close method,
Example -
java.io.FileInputStream class overrides finalize method and calls close method.
code of finalize() method of java.io.FileInputStream class >
protected void finalize() throws IOException {
if ((fd != null) && (fd != FileDescriptor.in)) {
/*
* Finalizer should not release the FileDescriptor if another
* stream is still using it. If the user directly invokes
* close() then the FileDescriptor is also released.
*/
runningFinalize.set(Boolean.TRUE);
try {
close();
} finally {
runningFinalize.set(Boolean.FALSE);
}
}
}
|
- Closing Database connections could also be done in this method in java.
- When application is heavy and it is likely to run out of space, we may override finalize method and call it periodically so that JVM reclaims space from all the discarded objects in java.
When not to override finalize method of class in java>
- finalize method execution is not assured - We must not override finalize method to write some critical code of application because methods execution is not assured. Writing some critical code in finalize method and relying on it may make application to go horribly wrong.
- Exception occurs in finally method it is ignored - When Exception occurs in finally method it is ignored because JVM itself executes the finalize method via garbage collector. So there is no scope of propagating exception further i.e. beyond JVM, hence exception is ignored and we may miss out on logging some serious Exception is application.
- using finally method costs us performance issues -
According to Joshua bloch’s Effective java >
The time to create and destroy a simple object is about 5.6 ns.
Adding a finalizer increases the time to 2,400 ns. In other words, it is about
The time to create and destroy a simple object is about 5.6 ns.
Adding a finalizer increases the time to 2,400 ns. In other words, it is about
430 times slower to create and destroy objects with finalizers.
- finalize methods are not chained like constructors, if overridden finalize method of subclass does not invoke finalize method of its superclass explicitly than superclass’s finalize() method will never be invoked.
SUMMARY >
In this core java tutorial we learned 13 salient features of finalize method in java. Finalize method is defined in which class in java. Why finalize is protected method in java? Who calls finalize method in java? When garbage collector calls finalize method in java? Can finalize method make object again available in java ? Perform clean actions in java. Java code in finalize method in java. Which thread invokes finalize method in java? What if Exception is thrown in finalize method in java? How to call finalize method explicitly in java? We can force early garbage collection in java. finalize methods are not chained like constructors in java. When not to override finalize method of class in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
final keyword in java - 20 salient features
Labels:
Core Java
Exceptions