1

I have a query related to new keyword.

1. What is the difference between

new Demo().abc();

and

Demo demo=new Demo();
demo.abc();
demo=null;

2. If I use first one then automatically garbage collector remove the memory?

My Question is:

how to remove memory for the below object:

new Demo().abc(); 
Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
mukesh
  • 13
  • 3

2 Answers2

5

Case -1 :

new Demo().abc();

Here, we are not maintaining any explicit reference to the newly created Demo instance. But inside the abc(), the this reference will point to the newly created instance. So, if the reference doesn't leak from abc(), as soon as the method returns, the newly created Demo instance will be ready for GC (As it becomes unreachable from any thread).

If there is a reference leak like this :

public void abc()
 {
  someOtherMethod(this); // starts another thread and does something else
  ...
 } 

In the above case, even when abc() returns, the Demo instance created could still be reachable and thus will not be eligible for GC.

Case -2 :

Demo demo=new Demo();
demo.abc();
demo=null;

Here as soon as you set demo to null and assuming abc() doesn't leak the reference of demo to some other thread, your demo instance will become unreachable as soon as you set it to null and thus, it will be eligible for GC.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • The `Demo` instance may even [get collected while `abc()` is running](http://stackoverflow.com/a/26645534/2711488). Well, after optimization, it might be the case that the code of `abc()` gets executed without a `Demo` instance ever be created. – Holger May 08 '15 at 09:53
  • @Holger - Yes. `JVM / JIT` has so many tricks up its sleeve.. :) . – TheLostMind May 08 '15 at 09:57
0

You don't have explicitly do anything to remove "new Demo().abc()" ,generally as long as there are no strong references to this Demo() object it'll get Garbage Collected by JVM.

Twaha Mehmood
  • 737
  • 3
  • 9
  • 26
  • Strong reference means?? – Prashant Apr 20 '15 at 10:14
  • Strong references are regular references like Integer a = new Integer(10); here 'a' is said to have strong reference to the object of Integer class. In your case "new Demo().abc()" you can get strong references as mentioned by 'TheLostMind' in Case 1 , i.e. ' someOtherMethod(this);.... ' – Twaha Mehmood Apr 20 '15 at 10:21
  • @tm.sauron You should explain the difference between a weak and strong reference. Why is a strong reference "strong"? – Carcigenicate Apr 20 '15 at 14:22