Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding garbage collection in java

I'm struggling with some garbage collection / allocation concepts in Java. I'll use the example below to illustrate my misunderstanding.

I have an Android application where I'm collecting data from sensors and storing the values in an array that never exceeds N samples. Using Android Studio I am able to watch a live view of Free vs Allocated memory. As my app runs I can watch the allocated memory slowly increase (and the free memory decrease). When the free memory approaches 0, the system runs a garbage collect and I see the Allocated memory drop significantly. Sometimes when the free memory approaches 0 the system will both do a garbage collection which will increase my allocated memory but will also increase the memory overhead.

1) If the allocated memory drops to 'original levels' when a garbage collection is performed does that mean that I do not have a memory leak? It is my understanding that a memory leak would mean that a garbage collection wouldn't be able to free the allocated memory.

2) Does the fact that allocated memory continues to increase even though the array size is limited to N samples indicate that I'm doing unnecessary allocation in my application? Once the array hits N samples I do an array.remove(0) prior to doing an array.add(). I would think that once N samples were in the array the allocated memory would not continue to increase.

like image 952
neonDion Avatar asked Mar 16 '26 07:03

neonDion


1 Answers

  1. You're correct.
  2. No. Every time you create a new sample, you need memory, and memory is thus allocated. Then you remove an old sample that used memory. This memory is not reclaimed immediately. It's only reclaimed when the garbage collection decides to run. That's when you see the allocated memory decrease.
like image 200
JB Nizet Avatar answered Mar 18 '26 21:03

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!