What is the difference between atomic / volatile / synchronized?

后端 未结 7 1085
长情又很酷
长情又很酷 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:10

    Synchronized Vs Atomic Vs Volatile:

    • Volatile and Atomic is apply only on variable , While Synchronized apply on method.
    • Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
    • Volatile variable store in RAM and it’s faster in access but we can’t achive Thread safety or synchronization whitout synchronized keyword.
    • Synchronized implemented as synchronized block or synchronized method while both not. We can thread safe multiple line of code with help of synchronized keyword while with both we can’t achieve the same.
    • Synchronized can lock the same class object or different class object while both can’t.

    Please correct me if anything i missed.

提交回复
热议问题