What Cases Require Synchronized Method Access in Java?

前端 未结 6 1146
醉酒成梦
醉酒成梦 2020-12-13 14:53

In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they

6条回答
  •  既然无缘
    2020-12-13 15:28

    If you want to make this class thread safe I would declare instanceVar as volatile to make sure you get always the most updated value from memory and also I would make the setInstanceVar() synchronized because in the JVM an increment is not an atomic operation.

    private volatile int instanceVar =0;
    
    public synchronized setInstanceVar() { instanceVar++;
    
    }
    

提交回复
热议问题