I have a ListView
in my app, that each row of the ListView
will need to load multiple images from remote resources.(i.e. the listview looks something like Instagram where each item contains at least one image).
I am implementing a two-level cache to improve the load image experience:
My first level memory cache is defined like this:
private Map<String, SoftReference<Bitmap>> l1ImageCache = new HashMap<String, SoftReference<Bitmap>>();
that I could keep some SoftReference of the image in memory to make the app lookup faster.My second level file cache is a folder on SD card or phone storage. Where I keep some of my already downloaded images in there. If the app could not find the image in the memory cache, it will come look up in the file directory. If the image file existing, it will load the file locally and put the file reference in to the memory cache as well.
If The app cannot find the needed image from either memory cache or file cache, it will use a
ImageDownloadWorker
(extendsAsyncTask
) to kick-off a thread and download the image. However, android could only allow as many as 128 threads per app, I am thinking a way to save some threads. The I created this data structure:// keep all pending downloads
private HashMap<String, ImageDownloadWorker> downloadTaskMap = new HashMap<String, ImageDownloadWorker>();
In which the String field will be the URL to download. This is to check if a thread to download a certain URL is already running, so I don't have to start another thread to download the same thing.
My question is According to the code, suppose one case that the app is about to download an image. The image is neither exiting in the memory cache, nor in the downloaded files folder. So the app checked the downloadTaskMap
if there's already a thread downloading this file, so that it doesn't have to create a new AsyncTask to the same thing. BUT how I can know when this pending download task has finished or not without blocking the main thread? If I do something like a wait/notify or some infinite while-loop, I was wondering this will block the UI thread?
Pointers are welcome, thank you!