If more than one thread can access a field should it be marked as volatile?

前端 未结 4 1341
借酒劲吻你
借酒劲吻你 2021-02-15 13:00

Reading a few threads (common concurrency problems, volatile keyword, memory model) I\'m confused about concurrency issues in Java.

I have a lot of fields that are acces

4条回答
  •  隐瞒了意图╮
    2021-02-15 13:39

    Well, you've read those other questions and I presume you've read the answers already, so I'll just highlight some key points:

    1. are they going to change? if not, you don't need volatile
    2. if yes, then is the value of a field related to another? if yes, go to point 4
    3. how many threads will change it? if only 1, then volatile is all you need
    4. if the answer to number 2 is "no" or more than one threads is going to write to it, then volatile alone is not enough, you'll probably need to synchronize the access

    Added:
    If the field reference an Object, then it will have fields of its own and all those consideration also applies to these fields.

提交回复
热议问题