0

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?

Komal-SkyNET
  • 193
  • 8
  • 4
    No, volatile doesn't synchronize access, thats what `synchronized` (or the other locks) is for. – tkausl Jun 26 '16 at 11:04
  • 4
    Volatile won't help you here. The volatile refers to the reference and not to the list's content. You should either lock the list using `synchronized` or have each thread maintain its own list (if possible) and combine the lists together when the processing is finished. – Guy Yafe Jun 26 '16 at 11:12
  • 1
    I recommend reading http://shipilev.net/blog/2016/close-encounters-of-jmm-kind/#_pitfall_adding_volatiles_closer_to_the_problem_helps (and if you have time, the entire article). – C4stor Jun 26 '16 at 11:14
  • This question provides some more useful info: http://stackoverflow.com/questions/9749746/what-is-the-difference-between-atomic-volatile-synchronized – Ravindra babu Jun 27 '16 at 09:10

2 Answers2

4

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.add(x);

the 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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

No, volatile wouldn't work here. Volatile keyword just makes sure that every read operation always get the latest updated value. Here you need to use synchronized.

Shubham Jain
  • 1,864
  • 2
  • 14
  • 24