What Cases Require Synchronized Method Access in Java?

前端 未结 6 1166
醉酒成梦
醉酒成梦 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:37

    In Java, operations on ints are atomic so no, in this case you don't need to synchronize if all you're doing is 1 write and 1 read at a time.

    If these were longs or doubles, you do need to synchronize because it's possible for part of the long/double to be updated, then have another thread read, then finally the other part of the long/double updated.

提交回复
热议问题