I have an EnumSet
which is final and immutable i.e. initialized once in the constructor.
Is the contains()
method on this EnumSet
thread safe? It is internally using an iterator to make the contains check. Hence if two threads are simultaneously calling the contains()
can the iterator position in one call effect other one? Or are the iterators having different instances in these two thread calls?
No, if two threads call contains()
at the same time, that will call iterator()
twice which will create two separate iterators.
If you were trying to share an iterator between two threads, that would not be a good idea.
Note that if you modify the set in one thread while iterating over it (e.g. via contains
) in another, then this bit of the docs comes into play:
The returned iterator is weakly consistent: it will never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the set that occur while the iteration is in progress.
See more on this question at Stackoverflow