Friday 30 August 2013

1. description:


One of the common mistakes developers often make is that never take care of Bitmap objects stored in a data structure like List, LinkedList, HashMap.
public class BitmapStorage {
    String mContent;
    ArrayList<Bitmap> mImages;
 
    // constructor to create the objects
    public BitmapStorage(String content, ArrayList<Bitmap> images) {
        mContent = content;
        mImages = images; // references
    }
}

Things seem to be fined IF developers try to release memory of this BitmapStorage object somewhere else. WHAT IF they FORGET? It’s gonna be really a mess, isn’t it?In my opinion, it is much better if providing such a way to handle memory in such a class.


  2. code:



package pete.android.study;
 
import java.util.ArrayList;
 
import android.graphics.Bitmap;
 
public class BitmapStorage {
    String mContent;
    ArrayList<Bitmap> mImages;
 
    // constructor to create the objects
    public BitmapStorage(String content, ArrayList<Bitmap> images) {
        mContent = content;
        mImages = images; // references
    }
 
    // call in order to free memory of Bitmap objects
    public void freeBitmaps() {
        for(Bitmap image: mImages) {
            // also, it's better to check whether it is recycled or not
            if(image != null && !image.isRecycled()) {
                image.recycle();
                image = null; // null reference
            }
        }
    }
 
    // the destructor should also handle the memory in case it still holds memory
    protected void finalize() {
        freeBitmaps();
    }
}

Like this, developers can freely choose to release memory whenever they feel done with theBitmapStorage objects and when they forget to do so, the destructor “finalize()” would handle the rest.
 3. note that:
  • make sure your Bitmap objects don’t link to any other things when recycling; it would be troublesome. Try to create a nice Bitmap objects live well in a life-cycle!
  4. conclusion:
  • Some information about Memory Leaks in Collections( List,LinkedList and HashMap).
  • know how to lease resources.
  • know how to avoid out of memory Error  in Collections( List,LinkedList and HashMap).
  5. about the post:
  • The next coming post will be on LRU cache and its usage. 
  •  The code seems to explain itself due to comments, and is very easy to understand.
  •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
  •  Hope you enjoy it!
Cheers,
Hamad Ali Shaikh