Java volatile modifier and synchronized blocks

前端 未结 3 821
忘了有多久
忘了有多久 2020-11-30 12:27

Does a variable that is accessed by multiple threads, but only inside synchronized blocks, need the volatile modifier? If not, why?

3条回答
  •  不知归路
    2020-11-30 12:57

    Blocks that synchronize on the same object (or method) are guaranteed to not be run at the same time. So as long as you synchronize to the same object, your variable will never have concurrent accesses, so it doesn't need special treatment.

    If your accesses aren't synchronized, then you have a race condition. Making the variable volatile can be correct for some primitive variables (I defer to other posts for better info on volaitle). If that isn't useful, you almost certainly have a bug.

提交回复
热议问题