Compound operations are unsafe in concurrent environment.
What compound operations are you performing?
- 1) You are checking whether
Map
contains a vector for a key - 2) You are putting a new
Vector
if no value is found
So this is a two step action and is compound, so it is unsafe.
Why are they not safe?
Because they are not atomic. Think of a scenario in which you have two threads.
Consider this timeline:
Thread 1 --- checks for == null -> true puts a new Vector
Thread 2 --- checks for ==null -> true puts a new Vector
Use putIfAbsent()
method on ConcurrentHashMap
, which provides you an atomic solution to what you are trying to perform.
ConcurrentHashMap#putIfAbsent()
References: