Question

This might be a stupid question but.. let's assume I have a class ContainerClass, if contains a HashSet that is accessed from several threads that add and also remove elements.. In one of these thread, let's call it thread 1, I execute the following code:

if(ContainerClass.hashSet.containsKey(keyId))
    int number = ContainerClass.hashSet.get(keyId);

Is it guaranteed that by the time the second line is executed, the element with the key keyId is still there? Or could this thread do the check in the if-statement, then be paused, then another thread alters the HashSet, and thread 1 gets a NullPointerException?

Was it helpful?

Solution

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();
}

OTHER TIPS

It's not guaranteed, thread safety refers to an objects data. If more than 1 thread can modify it at the same time then it is not thread safe. If you are concerned about performing logic on a shared object then must do the logic inside a locked statement (synchronized).

Thread safety has to do with shared, mutable state.

No one can decide from your snippet. If it's a class member you might want to guard it.

If it's a local variable, it's thread safe.

You can also make it safer by using a collection from the concurrent package

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top