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

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

    If a field is accessed by multiple threads, it should be volatile or final, or accessed only with synchronized blocks. Otherwise, assigned values may not be visible to other threads.

    A class has to be specifically designed for concurrent access by multiple threads. Simply marking fields volatile or final is not sufficient for thread-safety. There are consistency issues (atomicity of changes to multiple fields), concerns about inter-thread signaling (for example using wait and notify), etc.

    So, it is safest to assume that an object should be visible to only a single thread unless it is documented otherwise. Making all of your objects thread-safe isn't necessary, and is costly—in terms of software speed, but more importantly, in terms of development expense.

    Instead, software should be designed so that concurrent threads interact with each other as little as possible, preferably not at all. The points where they do interact need to be clearly identified so that the proper concurrency controls can be designed.

提交回复
热议问题