Singleton instance of Palette Color cache

476 views Asked by At

I have a list of CardViews that contain Bitmaps that return from the Network or from a LruCache.

I also run a Palette.from(Bitmap).generate() operation on these bitmaps. This is expensive. I would like to save these palette colors in a HashMap<...> of some sort.

This is the idea that I have, use HashMap<String, Integer> for each item name, and its corresponding color value.

If the name changes then change the color value. The items in the list do not change that often so that is why I am considering using a HashMap<String, Integer>.

Secondly save this HashMap somewhere, maybe on the disk so when the user starts the app again there is no need to generate the Palette swatch if it already exists (and matches the name).

I am thinking to implement it this way:

public class PaletteCache {

    private static PaletteCache sPaletteCache;
    private static HashMap<String, Integer> mCache;

    private PaletteCache() { 
        loadCache();
    }

    public static PaletteCache getInstance() {
        if (sPaletteCache == null)
            sPaletteCache = new PaletteCache();
        return sPaletteCache;
    }

    private static void loadCache() {
        // Load the HashMap from disk if present
    }

    public static int getVibrantColor(String itemName) {
        return mCache.get(itemName);
    }

    public static void setColor(String itemName, int color) {
        mCache.put(itemName, color);
    }

}

Any criticisms of this approach? If so what are alternatives?

1

There are 1 answers

9
Anonymous Coward On BEST ANSWER

That approach to lazy initialization of a singleton will fail in multithread applications.

An alternative which does not have that problem and does not carry a performance hit is using an enum to implement the singleton.

public enum PaletteCache
{
    INSTANCE;

    private static HashMap<String, Integer> mCache;

    private PaletteCache() {
        loadCache();
    }

    public static PaletteCache getInstance() {
        return INSTANCE;
    }

    private static void loadCache() {
        // Load the HashMap from disk if present
    }

    public static int getVibrantColor(String itemName) {
        return mCache.get(itemName);
    }

    public static void setColor(String itemName, int color) {
        mCache.put(itemName, color);
    }

}