Search code examples
javamultithreadinglockingfinalreadonly

Readonly objects and multithreading


after using the questions and answers of this great page for over 2 years now, I decided to join the community!

Now to my question:

I had a discussion with a friend the other day: We think, that variables which are readonly or are only read by the threads don't need a lock or anything else to assure the right values are read. But what is with other objects like arraylists, hashmaps? Do I know for certain, that multiple threads can use values of any objects at once without problems?

Don't be too harsh on me, if I asked the wrong way or missed something obvious in my thought-process (still thinking about atomicity...). I'm grateful for any answer :)


Solution

  • If the construction of the Map / List is thread-safe and if the the ArrayList or HashMap is NOT changed after construction, then yes, your threads will be able to read the data correctly. If new data is added or existing data modified, then without proper synchronization, there is no guarantee that new changes will be visible to other threads.