Overriding finalize method:
class Test
{
Test()
{
System.out.println("Created : " + this);
}
protected void finalize()
{
System.out.println("Deleted : " + this);
}
}
class GCDemo
{
public static void main(String[] args)
{
new Test();
new Test();
}
}
- In the above application, we have created unreferenced objects.
- GC thread is not invoking finalize() method to delete those objects.
- GC thread invokes by JVM only when the memory is running low.
- GC thread will not execute continuously in the application.
- When JVM executes GC thread in the background continuously that will decrease application performance.
Creating thousands of unreferenced objects to check the execution of finalize() method:
class Test
{
Test()
{
System.out.println("Created : " + this);
}
protected void finalize()
{
System.out.println("Deleted : " + this);
}
}
class GCDemo
{
public static void main(String[] args)
{
for (int i=1 ; i<=8000 ; i++)
{
new Test();
}
}
}
Note: increase the count of loop if you cannot see the execution of finalize method in your system.