I have an ArrayList 'X' that's passed to multiple threads where each thread adds more data to this ArrayList 'X'using addAll(). Obviously there are multi-threading issues here, one option would be to make the addAll() portion of the code 'synchronized' (or) use copyOnWriteArrayList.
But my question here is, would declaring this ArrayList 'volatile' achieve the same purpose? Does JVM order these read/write instructions accordingly and prevent multi-threading issues?
would declaring this ArrayList 'volatile' achieve the same purpose?
You can't actually. When you write
volatile ArrayList list;
this makes the
list reference volatile, not the underlying ArrayList. It also means that when you do
list is read, so you only get a read barrier not a write barrier.
NOTE: This doesn't make the operation atomic either which is what you really need, but without a write barrier you might not even see this operation in another thread.
Does JVM order these read/write instructions accordingly and prevent multi-threading issues?
It will order the reads accordingly, but not in a way which can be used to avoid multi-threading issues in this case. i.e. there is no way to make this work with volatile, let alone assume the JVM will do what you want without having to worry about it.
synchronized by comparison can be used correctly. You can still get it wrong, it's not fool proof, but you have a good chance of getting it right.