Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java collections safe if read but not modified on multiple threads?

Can I use the standard Collections classes (as opposed to the concurrent ones) as long as I ensure the code makes no data changes on multiple threads. The code that I'm talking about is completely under my control, and I'm not mutating it after the initial (single-threaded) population phase.

I know that some classes such as DateFormat are not threadsafe because they store intermediate states as they are being used. Are the collections (ArrayList, Tree Map, etc.) safe though?

like image 992
ᴇʟᴇvᴀтᴇ Avatar asked Jan 11 '23 14:01

ᴇʟᴇvᴀтᴇ


1 Answers

Collections are generally safe for concurrent reading, assuming they are safely published. Apart from that, I'd also recommend the collections are wrapped with the unmodifiable wrappers (such as Collections.unmodifiableList) and that the elements in them are immutable (but you probably already knew this).

like image 186
gustafc Avatar answered Jan 20 '23 06:01

gustafc