Memory Leak in getScaledBitmap()?


#1

In Listing 16.9, we create a variable options:

BitmapFactory.Options options = new BitmapFactory.Options();

then later, we point options at some new space:

options = new BitmapFactory.Options();

Is the space taken up by the original new BitmapFactory.Options(); now lost since nothing is pointing to it, or does Java automatically handle this?


#2

Java will handle that for you. In java, the garbage collector runs periodically looking for chunks of memory that nothing has a reference to anymore. When it finds one, the garbage collector frees up that memory.

Once we replace the original options variable with a new one, we no longer have a reference to that first piece of memory and it will be automatically cleaned up.


#3

Excellent! Thanks, @cstewart.


#4

can you still assign a null value to the variable to force garbage collection
ex. options = null ?


#5

Assigning it to null won’t make a significant difference over freeing up references to the object. Manually setting variables to null is going to complicate your code without adding any benefit.