In Java, do I need to declare my collection synchronized if it's read-only?

后端 未结 5 1211
挽巷
挽巷 2021-02-12 12:30

I fill a collection one single time when my J2EE webapp starts. Then, several thread may access it at same time but only to read it.

I know using a synchronized collecti

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-12 13:00

    It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values.

    The reason for this is the Java Memory Model, if you wanna know more read the section "Visibility" at this link: http://gee.cs.oswego.edu/dl/cpj/jmm.html

    And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks Michael Bar-Sinai, I didn't know such collections existed in the standard JDK).

    Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book Java Concurrency in Practice.

提交回复
热议问题