Thread safety in Java class

前端 未结 4 749
陌清茗
陌清茗 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:24

    When you have two method modifying/accessing a non-volatile variable it is never thread safe. If you want to have just one method you can try :

    synchronized int getAndSet(int x, boolean set) {
        if (set) this.x = x;
        return this.x;   // param x is for set
    } 
    

提交回复
热议问题