0

Does making an object reference null, releases a memory occupied by that object. For example:

public static void main(String[] args) {

    ArrayList<Billing_productModel> list = new ArrayList<>();
    for(int i=0;i<100;i++){
        list.add(new BillingProductModel());
    }
    System.out.println("Size of List : "+list.size());
    list = null;
    while(true);
}

Here I have created an Arraylist and added 100 new objects to it. If I make object reference (list) null, does Garbage Collecter clears a memory allocated to list.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
  • It doesn't release memory immediately because the object still exists after the variable pointing to it stops doing so. Memory release will only take place when the object is garbage-collected. And yes, if `list` was the only variable pointing to it, that array list instance is eligible for garbage collection. – ernest_k Jun 09 '18 at 12:06
  • Yes. It'd release when gc would run. – Shanu Gupta Jun 09 '18 at 12:07
  • @ShanuGupta: how can you say that as you have no idea if that same object is referred to elsewhere in the program. GC is never as simple as just setting a reference variable to null. – Hovercraft Full Of Eels Jun 09 '18 at 12:34
  • @HovercraftFullOfEels I was talking about the program in question. It has anonymous objects. – Shanu Gupta Jun 09 '18 at 12:39

0 Answers0