I believe you need to synchronize even if you are just calling setUPayerNums.contains(sPayerUnitNum).
Internally HashSet has a HashMap which goes through the entries in the relevant bucket to lookup the key passed. This means it is iterating a sub-set of the values. So if another thread is manipulating the Set you are not guaranteed the correct value and you could get some concurrency exceptions. I think the warning: "Failure to follow this advice may result in non-deterministic behavior." applies to the code you are trying.
Adi Pandit wrote:I believe you need to synchronize even if you are just calling setUPayerNums.contains(sPayerUnitNum).
Internally HashSet has a HashMap which goes through the entries in the relevant bucket to lookup the key passed. This means it is iterating a sub-set of the values.
No, that's wrong. The advice quoted in the original post is about writing code which iterates over the set. It doesn't require the reader to know the internal implementation of other methods and to determine whether they might be iterating over something. It simply means what it says, no more than that.
If the contains() method actually does iterate over the set, or part of it, then the internal code will synchronize accordingly. That's precisely what the synchronizedSet method is for. All you have to worry about is code that you write. You don't have to second-guess code written by the Java API coders.
Amandeep Singh wrote:1) Yes, the advice is about iterating. What i thought is- they just want to give a idea- it may apply to other scenario- when using the contains method.
The set that is returned from the synchronizedSet() method returns a set that synchronizes all the method calls for you. The reason the iterator is a special case is because you don't want the set to change in-between many calls of the iterator, hence, you need to hold the lock to the set, for the full duration of the loop.
Amandeep Singh wrote:2) If we are just checking through contains method without using a synchronized block. So what is the use of making a synchronizing a set? (Just to make sure, only 1 thread makes a set at a time.)
Without using the synchronizedSet() method, then your set is not synchronized, and hence, you need to use the synchronized block for all the calls to the set. With the synchronizedSet(), then you only need to externally synchronize for the iterator, or any other operation that requires thread safety across mulitple calls to the set.