Is iinc atomic in Java?

后端 未结 6 1026
情话喂你
情话喂你 2020-12-30 12:30

I know increment operation is not atomic in C++ without locking.

Will JVM add any lock on its implementation of iinc instruction?

6条回答
  •  粉色の甜心
    2020-12-30 13:18

    {Although there already is an accepted answer, I wanted to clear something up, thus the late and technically unnecessary answer}

    The answer to your question depends on whether you mean the IINC instruction or, what other answers are referring to, the ++ operator.

    Using ++ on a static or instance field is nothing more than get, increment, and set, thus it is not atomic (the other answers explain this in more detail).

    But

    Since you asked if the IINC instruction is atomic, this is not the real answer. In fact, none of the answers to this question address the instruction, all of them seem to be based around the operator being used on instance or static fields.


    The IINC instruction only operates on local variables. As the name suggests, they are only local, and only accessible from a very limited scope. Thus, it is not possible to access a local variable from another Thread. This means that it doesn't matter whether or not the instruction is atomic.

提交回复
热议问题