System.gc() in Java

Previous
Next

In the following example, finalize method doesn’t execute implicitly as the memory is not running low:

class Test
{
	Test()
	{
		System.out.println("Created : " + this);
	}
	protected void finalize()
	{
		System.out.println("Deleted : " + this);
	}
}
class GCDemo 
{
	public static void main(String[] args) throws Exception
	{
		for (int i=1 ; i<=10 ; i++)
		{
			new Test();
			Thread.sleep(1000);
		}
	}
}

System.gc():

  • System class is providing pre-defined function called gc().
  • gc() method invokes Garbage collector.
  • We invoke Garbage collector explicitly when we want to perform garbage collection though the memory is not running low.
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<=10 ; i++)
		{
			new Test();
			System.gc();
			try{
				Thread.sleep(1000);
			}catch(Exception e){ }
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form