How to prevent an object from getting garbage collected?

后端 未结 11 1959
太阳男子
太阳男子 2020-12-02 13:17

How to prevent an object from getting garbage collected?

Are there any approaches by finalize or phantom reference or any other approaches?

I was asked this

11条回答
  •  天涯浪人
    2020-12-02 13:53

    The key point is if we set the real reference variable pointing to the object null,although we have instance variables of that class pointing to that object not set to null. The object is automatically eligible for garbage collection.if save the object to GC, use this code...

    public class GcTest {
    
        public int id;
        public String name;
        private static GcTest gcTest=null;
    
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
    
            System.out.println("In finalize method.");
            System.out.println("In finalize :ID :"+this.id);
            System.out.println("In finalize :ID :"+this.name);
    
            gcTest=this;
    
        }
    
        public static void main(String[] args) {
    
            GcTest myGcTest=new GcTest();
            myGcTest.id=1001;
            myGcTest.name="Praveen";
            myGcTest=null;
    
            // requesting Garbage Collector to execute.
            // internally GC uses Mark and Sweep algorithm to clear heap memory.
            // gc() is a native method in RunTime class.
    
            System.gc();   // or Runtime.getRuntime().gc();
    
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("\n------- After called GC () ---------\n");
            System.out.println("Id :"+gcTest.id);
            System.out.println("Name :"+gcTest.name);
    
    
        }
    
    }
    

    Output :

    In finalize method.
    In finalize :ID :1001
    In finalize :ID :Praveen

    ------- After called GC () --------

    Id :1001
    Name :Praveen

提交回复
热议问题