6

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.
Kara
  • 6,115
  • 16
  • 50
  • 57
TIER 0011
  • 971
  • 3
  • 8
  • 13

4 Answers4

9

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 2
    Good answer. The nulling of any object removes the reference to an object and makes it a candidate for garbage collection. +1 – yams Sep 04 '13 at 16:28
1

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.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

Well all objects will be collected by Garbage collector automatically when they are no longer referenced. You dont have to woory about it. Still if you want you can assign null to array and on the next run of GC, it memory which was allocated to array will be deallocated itself. For running GC explicitly, you can do

    java.lang.Runtime.getRuntime().gc();
M Sach
  • 33,416
  • 76
  • 221
  • 314
0

Object De Allocation should occur upon closing or opening by nulling out the object. JUnit tests do assertGC on objects to make sure all objects have been garbage collected. Java will not garbage collect an item if it has a reference. I would strongly recommend doing JUnit testing.

yams
  • 942
  • 6
  • 27
  • 60