What is the difference between atomic / volatile / synchronized?

后端 未结 7 1069
长情又很酷
长情又很酷 2020-11-22 16:56

How do atomic / volatile / synchronized work internally?

What is the difference between the following code blocks?

Code 1

private int counter         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 17:27

    A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.

    Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.

    Hope the explanation is clear enough.

提交回复
热议问题