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

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

    If you have to ask, use locks. volatile can be useful in some cases, but it's very, very difficult to get right. For example:

    class Foo {
      private volatile int counter = 0;
      int Increment() {
        counter++;
        return counter;
      }
    }
    

    If two threads run Increment() at the same time, it's possible for the result to be counter = 1. This is because the computer will first retrieve counter, add one, then save it back. Volatile just forces the save and load to occur in a specific order relative to other statements.

    Note that synchronized usually obviates the need for volatile - if all accesses to a given field are protected by the same monitor, volatile will never be needed.

    Using volatile to make lockless algorithms is very, very difficult; stick to synchronized unless you have hard evidence that it's too slow already, and have done detailed analysis on the algorithm you plan to implement.

提交回复
热议问题