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

前端 未结 4 1356
借酒劲吻你
借酒劲吻你 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:32

    The short answer is no. Threading issues require more thought and planning than this. See this for some limitations on when volatile helps for threading and when it does not. The modification of the values has to be properly synchronized, but very typically modification requires the state of more than one variable at a time. Say for example you have variable and you want to change it if it meets a criteria. The read from the array and the write to the array are different instructions, and need to be synchronized together. Volatile is not enough.

    Consider also the case where the variable references a mutable object (say an array or a Collection), then interacting with that object will not be thread safe just because the reference is volatile.

提交回复
热议问题