No, it is not guaranteed.
To make it guaranteed, you'd have to consistently synchronize access to hashSet
(presumably it's a java.util.HashMap
) in order to prevent another thread from modifying the map between these operations.
Alternatively, there are ConcurrentMap
implementations that, unlike java.util.HashMap
are intended for use by multiple threads. They support an additional set of operations, like putIfAbsent()
so that you can atomically check and conditionally modify the map.
Even if you simplify your code to eliminate the unnecessary check, it's still not safe to share a java.util.HashMap
across threads without a memory barrier. For example, this isn't safe if another thread might modify the map asynchronously:
Integer tmp = ContainerClass.hashSet.get(keyId);
if (tmp != null) {
int number = tmp.intValue();
}