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

后端 未结 5 1212
挽巷
挽巷 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:01

    In the general case, you should. This is because some collections change their internal structure during reads. A LinkedHashMap that uses access order is a good example. But don't just take my word for it:

    In access-ordered linked hash maps, merely querying the map with get is a structural modification The Linked hash map's javadoc

    If you are absolutely sure that there are no caches, no collection statistics, no optimizations, no funny stuff at all - you don't need to sync. In that case I would have put a type constraint on the collection: Don't declare the collection as a Map (which would allow LinkedHashMap) but as HashMap (for the purists, a final subclass of HashMap, but that might be taking it too far...).

提交回复
热议问题