What is the “volatile” keyword used for?

前端 未结 8 935
一个人的身影
一个人的身影 2020-11-28 19:35

I read some articles about the volatile keyword but I could not figure out its correct usage. Could you please tell me what it should be used for in C# and in

相关标签:
8条回答
  • 2020-11-28 20:30

    Consider this example:

    int i = 5;
    System.out.println(i);
    

    The compiler may optimize this to just print 5, like this:

    System.out.println(5);
    

    However, if there is another thread which can change i, this is the wrong behaviour. If another thread changes i to be 6, the optimized version will still print 5.

    The volatile keyword prevents such optimization and caching, and thus is useful when a variable can be changed by another thread.

    0 讨论(0)
  • 2020-11-28 20:30

    When you are reading data that is non-volatile, the executing thread may or may not always get the updated value. But if the object is volatile, the thread always gets the most up-to-date value.

    0 讨论(0)
提交回复
热议问题