1

Whit very simple example I want to ask you about garbage collection in Java. I have few object in one arrayList. In some point I want to remove one object from the arrayList and at the same time I want to destroy this object. How to do this? Please help!

Here is example:

class SomeClass{

    public SomeClass()
    {

    }
}
public class Test 
{

    public static void main(String[] args)  throws Throwable
    {
        SomeClass a = new SomeClass();
        SomeClass b = new SomeClass();

         ArrayList<SomeClass> arr = new ArrayList<SomeClass>();

          arr.add(a);
          arr.add(b);

          //this doesn't work
          SomeClass tmp =  arr.remove(0);
          tmp = null;

          /* I want to do something like this. I want to remove the object from arrayList
              and at the same time to clean this object. Something like this:

              arr.remove(0) = null;
          */

          System.out.println(a);
    }

}
Pang
  • 9,564
  • 146
  • 81
  • 122
BigApp7e
  • 11
  • 1
  • 3
  • Java manages GC on your behalf, even if you set the `object` to `null` value that won't destroy the object, it is only setting its reference to the null. Actual object still remains in memory until Java GC kicks in, even then it is not sure. – Sandeep Singh Mar 06 '18 at 06:34
  • By calling `System.gc()` you can hint to the System that you would a Garbage Collection to occur. – Scary Wombat Mar 06 '18 at 06:37

3 Answers3

2

Java is a Garbage collected language, we don't need to or can free memory manually. Once you de-reference an object, the next time GC runs it will mark or sweep that object. You cannot manually destroy an object, you can only de-reference it.

If you need hooks before an object is destroyed, there is a finalize method that can be overridden.

@Override protected void finalize() throws Throwable {
   // clean up logic
}
Sid
  • 4,893
  • 14
  • 55
  • 110
0

Java runs GC asynchronously. So although you have no reference to the object, only in the next iteration of GC that objects gets removed from heap.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

If you are not using this object then no need to do anything garbage collector will take care about it. it will destroy automatically.