Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing Objects in an Array for Java Garbage Collection

I have done some research on the java garbage collector and understand that an object who is no longer referenced will/should be handled by the garbage collector. In terms of arrays-of-objects, I am aware that assigning a new object to a location in the array does not properly deallocate the previously allocated object.

  1. I would like to know how to remove and properly deallocate an object from an array at location x and assign a new object to the same array at location x.
  2. I would also like to know how to properly deallocate the array itself.
like image 651
TIER 0011 Avatar asked Feb 09 '13 16:02

TIER 0011


People also ask

Which method is used to garbage collect an object in Java?

finalize() method in Java is a method of the Object class that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the objects from memory. finalize() method is called by default for every object before its deletion.

How is garbage collection controlled in Java?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

How do I make sure an object is not garbage collected?

If there is still a reference to the object, it won't get garbage collected. If there aren't any references to it, you shouldn't care. In other words - the garbage collector only collects garbage. Let it do its job.


2 Answers

Setting an object in an array to null or to another objects makes it eligible for garbage collection, assuming that there are no references to the same object stored anywhere.

So if you have

Object[] array = new Object[5];
Object object = new Object() // 1 reference
array[3] = object; // 2 references
array[1] = object; // 3 references


object = null; // 2 references
array[1] = null; // 1 references
array[3] = new Object(); // 0 references -> eligible for garbage collection

array = null; // now even the array is eligible for garbage collection
// all the objects stored are eligible too at this point if they're not
// referenced anywhere else

The garbage collection rarely will reclaim memory of locals though, so garbage collection will mostly happen already outside of the scope of the function.

like image 158
Jack Avatar answered Sep 22 '22 12:09

Jack


In java you don't need to explicitly deallocate objects, regardless of whether they are references from array, or simple field or variable. Once object is not strongly-reachable from root set, garbage collection will deallocate it sooner or later. And it is usually unreasonable to try helping GC to do its work. Read this article for more details.

like image 38
Mikhail Vladimirov Avatar answered Sep 19 '22 12:09

Mikhail Vladimirov