Thread safety in Java class

前端 未结 4 755
陌清茗
陌清茗 2020-12-15 06:30

Why is this java class not Thread safe.

class TestClass {  
   private int x;

   int get() {
       return x;
   }

   void set(int x) {
       this.x = x;
         


        
4条回答
  •  情深已故
    2020-12-15 07:23

    Because the field 'x' is not declared volatile there is no requirement for the JVM to ensure that 'x' is visible to all other threads. I.e. if one thread is constantly reading the value of 'x' and another thread is writing it, it is possible that the reading thread will never "see" the value change.

    A synchronized keyword is not required, but will work as it will create the necessary memory barrier/cache flush to ensure 'x' is visible, but using the volatile keyword in this case will be more efficient.

提交回复
热议问题