Memory Leak using ArrayList

I have the following code in a draw loop. I added code to monitor the memory usage and it eventually allocates all memory reguardless of how much memory I set in Preferences.. Does a ArrayList .remove() call only delete the value but not delete the object memory itself at that location? I have put a loop working backwards thru the entire list and I still get the same result. Memory is never freed. If I comment out this code memory behaves as expected...so some how the new, add, remove sequence is not free the memory allocated with the new call....

void draw() {
...
      if (totalDrops % 2 == 0) {
        face = new Face(game.levelCount);
        faceList.add(face);
        faceList.remove(face);
      } else
      {
        face = new Face(game.levelCount);
        faceList.add(face);
        faceList.remove(face);
      }

...
  maxMemory = int(Runtime.getRuntime().maxMemory()/MEGABYTE);
  totalMemory = int(Runtime.getRuntime().totalMemory()/MEGABYTE);
  freeMemory = int(Runtime.getRuntime().freeMemory()/MEGABYTE);
  percentage = int((float)freeMemory/totalMemory*100);

 text("max: " + maxMemory + " | total: " + totalMemory + " (" + percentage + "%)" + " | free: " + freeMemory, 15, 200);
...
}

in another sample program, the memory seems to be freed correctly - what is the difference?

void draw() { ... for (int i=1; i < maxItems; i++) {

ArrayObject value = new ArrayObject();
sampleList.add(value);

}

for (int i = sampleList.size () - 1; i >= 0; i--) { sampleList.remove(i);

... }

Answers

  • edited May 2015

    Does a ArrayList's remove() call only delete the value but not delete the object memory itself at that location?

    • Java doesn't allow us to directly deallocate objects.
    • Most we can do is send a hint for it via System.gc();
    • Method remove() simply remove the object's reference from the container.
    • But the object keeps on living until Java's GC decides to get rid of it.
    • Just make sure there ain't no other variables or containers holding the object's reference.
Sign In or Register to comment.