I am considering using EnumMap
in a concurrent environment. However, the environment is atypical, here's why:
EnumMap
is always full: there are no unmapped keys when the map is exposed to the concurrent environment- Only
put()
andget()
operations will be used (no iterating over, noremove()
, etc.) - It is completely acceptable if a call to
get()
does not reflect a call toput()
immediately or orderly.
From what I could gather, including relevant method source code, this seems to be a safe scenario (unlike if iterations were allowed). Is there anything I might have overlooked?
In general, using non-thread-safe classes across threads is fraught with many problems. In your particular case, assuming safe publication after all keys have had values assigned (such that
map.size() == TheEnum.values().length
), the only problem I can see from a quickish glance ofEnumMap
's code in Java 1.6 is that aput
may not ever get reflected in another thread. But that's only true because of the internals ofEnumMap
's implementation, which could change in the future. In other words, future changes could break the use case in more dangerous, subtle ways.It's possible to write correct code that still contains data races -- but it's tricky. Why not just wrap the instance in a
Collections.synchronizedMap
?