Multiple instances of ThumbnailDownloader


#1

I’ve noticed that the photoGallery app is too slow when downloading thumbnails because it was downloading them one by one. To speed it, I decided to fire up multiple FlickrFetcher.getUrlBytes(url) at once in different threads.

My solution was to change mThumbnailDownloader into an array

    private final static int THUMBNAIL_DOWNLOADERS = 10;
    private ThumbnailDownloader<GalleryItem> mThumbnailDownloader[];

and in onCreate

        mThumbnailDownloader = new ThumbnailDownloader[THUMBNAIL_DOWNLOADERS];
        for (int i = 0; i < mThumbnailDownloader.length; i++) {
            mThumbnailDownloader[i] = new ThumbnailDownloader<GalleryItem>(new Handler());
            mThumbnailDownloader[i].setListener(galleryItemListener);
            mThumbnailDownloader[i].start();
            mThumbnailDownloader[i].getLooper();
        }

and in GalleryItemAdapter.getView

mThumbnailDownloader[i%THUMBNAIL_DOWNLOADERS].queueThumbnail(item, item.getUrl());

of course I am also clearing the queue and quitting all the instances.

Is this a good practice? I wish HandlerThread had multiple loopers. That would make the code cleaner. Is there an easy way to make a class which extends HandlerThread have multiple loopers?


#2

one handlerThread can only have one looper.

in the origin code of HandlerThread class

public class HandlerThread extends Thread {
    Looper mLooper;

    @Override
    public void run() {
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
    }
    ...
}

and use a ThreadLoacl instance to store a map of key-value pairs, the key is the handlerThread and the value is the looper