Java Garbage Collection

reference: http://www.studytonight.com/java/garbage-collection.php

Garbage Collection

In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is calledGarbage Collection. This is accomplished by the JVM.

 

Can the Garbage Collection be forced explicitly ?

No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.

 

finalize() method

Sometime an object will need to perform some specific task beofre it is destroyed such as closing an open connecton or releasing any resources held. To handle such situation finalize() method is used. finalize() method is called by garbage collection thread before collection object. It is the last chance for any object to perform cleanup utility.

protected void finalize(){

}

1. finalize() method is defined in java.lang.Object class, therefore it is avaliable to all the classes.

2. finalize() is decalred as proteced inside Object class

3. finalize() method gets called onlu once by GC thread

 

gc() Method

gc() method is used to call garbage collector explicitly. However gc() method does not gurantee that JVM will perform the garbage collection. It request the JVM for garbage collection. This method is present in System and Runtime class.

public class Test
{
    
    public static void main(String[] args)
    {
        Test t = new Test();
        t=null;
        System.gc();
    }
    public void finalize()
    {
        System.out.println("Garbage Collected");
    }
}



 

转载于:https://www.cnblogs.com/morningdew/p/5618575.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值