0

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:

  1. 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.

  2. 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.

  3. If The app cannot find the needed image from either memory cache or file cache, it will use a ImageDownloadWorker (extends AsyncTask) 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!

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

1 Answers1

0

First of all you do not need to write all that on your own, there are many solutions for image lazy loading available for Android. See here, or even better off here.

As for the async tasks - they will not be running simultanously, you should use either ordinary Thread or executeOnExecutor as the latest update of this answer suggest (otherwise you will not get parallelism on newer devices). By the way I think you will find that answer useful in more than single way.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135