Is iteration via Collections.synchronizedSet(…).forEach() guaranteed to be thread safe?

前端 未结 3 1924
后悔当初
后悔当初 2021-02-02 09:00

As we know, iterating over a concurrent collection is not thread safe by default, so one cannot use:

Set set = Collections.synchronizedSet(new HashSet&l         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 09:28

    As you wrote, judging by implementation, forEach() is thread-safe for the collections provided with JDK (see disclaimer below) as it requires monitor of mutex to be acquired to proceed.

    Is it also thread safe by specification?

    My opinion - no, and here is an explanation. Collections.synchronizedXXX() javadoc, rewritten in short words, says - "all methods are thread-safe except for those used for iterating over it".

    My other, although very subjective argument is what yshavit wrote - unless told/read that, consider API/class/whatever not thread-safe.

    Now, let's take a closer look at the javadocs. I guess I may state that method forEach() is used to iterate over it, so, following the advice from javadoc, we should consider it not thread-safe, although it is opposite to reality (implementation).

    Anyway, I agree with yshavit's statement that the documentation should be updated as this is most likely a documentation, not implementation flaw. But, no one can say for sure except for JDK developers, see concerns below.

    The last point I'd like to mention within this discussion - we can assume that custom collection can be wrapped with Collections.synchronizedXXX(), and the implementation of forEach() of this collection can be... can be anything. The collection might perform asynchronous processing of elements within the forEach() method, spawn a thread for each element... it is bounded only by author's imagination, and synchronized(mutex) wrap cannot guarantee thread-safety for such cases. That particular issue might be the reason not to declare forEach() method as thread-safe..

提交回复
热议问题