javacollectionsthread-safetymultimapenum-map

How to init EnumMap which uses another map as value


private static EnumMap<Edition, ListMultimap<KeyClass, ValueClass>> 
   valueByKeyPerEdition = Collections.synchronizedMap(
     new EnumMap<Edition, ListMultimap<KeyClass, KeyClass>>());

I want to init a thread-safe map of map. Firstly, I tried the init function above, but it says no suitable constructor found for EnumMap. And then I tried to add Edition.class, result in new EnumMap<Edition, ListMultimap<KeyClass, KeyClass>>()); , it still doesn't work. Error message is incompatible types: no instance(s) of type variable(s) K,V exist so that Map<K,V> conforms to EnumMap<Edition, ListMultimap<KeyClass, ValueClass>>.

Could anyone help? Thanks in advance! I know the basic of Generic, but really confuse about how valueByKeyPerEdition should be initilized.


Solution

  • Collections.synchronizedMap() returns a different Map implementation that delegates to its argument, so you need to change the field type to Map instead of EnumMap:

    private static Map<Edition, ListMultimap<KeyClass, ValueClass>> valueByKeyPerEdition =
            Collections.synchronizedMap(new EnumMap<>(Edition.class));
    

    Note that synchronizing the outer map doesn't ensure the thread-safety of its contents.