java garbage collection and null reference

前端 未结 6 1729
梦谈多话
梦谈多话 2020-12-20 05:27

In my studying for OCJP I came across the following question:

class CardBoard {
           Short story = 200;
           CardBoard go(CardBoard cb) {
                


        
6条回答
  •  囚心锁ツ
    2020-12-20 06:25

    c3 has no references to an object,it is just to make some confusion.

    We have created two objects c1 and c2, what we are missing out is wrapper objects of type Short, so basically we have created four objects in total.

    When we are making c1 = null it means that short object which we are accessing using c1 is available for GC, not the short object which we can access using c2.

    This can be verified using following code:

    public class CardBoard {

    Short story = 200;
    
    CardBoard go(CardBoard cb) {
        cb = null;
        return cb;
    }
    
    public static void main(String[] args) {
        Runtime run = Runtime.getRuntime();
    
        CardBoard c1 = new CardBoard();
        CardBoard c2 = new CardBoard();
        CardBoard c3 = c1.go(c2);
    
        // System.out.println(run.freeMemory());
    
        run.gc();
        // System.out.println(run.freeMemory());
    
        c1.story = 100;
    
        System.out.println(c1.story);
        c1 = null;
        run.gc();
    
        System.out.println(c2.story);
    
    }
    

    }

    output: 100 200

    which means that c1 and Short story which we can access from c1 is available for garbage collection not Short story of c2.

提交回复
热议问题