Java EE doesn't provide you with any solution for resource contention over your own resources; but Java does.
For your case, using a ConcurrentHashMap
may solve most of your problems. A ConcurrentHashMap
will protect you against cases in which two threads update the Map
in exactly the same time (which, in a HashMap
, is likely to throw an exception). It offers you the same methods from the Map
interface as HashMap
, plus a few useful methods from the ConcurrentMap
interface (such as replace
and putIfAbsent
). For most needs, this option is sufficient.
Having said that, sometimes, you might need to use the synchronized
keyword even if you're using a ConcurrentHashMap
. For example, consider a case when you'd like to put two items into the Map
, but it's extremely important to you that, while the current thread is issuing the two put
s, no other thread will get
or put
from the Map. In other words, ConcurrentHashMap
only isolates access for each call individually; for cases when you need the isolation to span multiple calls, use synchronized
.
EDIT following @Arjan's comment: if you're using JavaEE 6.0 onwards, you can use @Singleton
in combination with @Lock
to achieve a similar effect.