samedi 15 octobre 2016

Thread safe Lazy loading of a static map

I'm trying to lazily initialize a map in a thread safe way. I've come up with this following the initialization-on-demand holder idiom:

private static class NameIndexMapHolder {
    private static final Map<String, Long> NAME_INDEX_MAP;
    static {
        Map<String, Long> map = new HashMap<>();
        map.put("John", 3424534643);
        map.put("Jane", 4328759749);
        NAME_INDEX_MAP = Collections.unmodifiableMap(map);
    }
}

public static Map<String, Long> getNameIndexMap() {
    return NameIndexMapHolder.NAME_INDEX_MAP;
}

Does this work? Is it thread safe? From what I've read this works for Singletons only. The only other alternative I've read is double checked locking which seems to have its own issues.

Aucun commentaire:

Enregistrer un commentaire