Java volatile modifier and synchronized blocks

前端 未结 3 816
忘了有多久
忘了有多久 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:53

    No. When you work within a synchronized block, all cached variables are synchronized on access, since it creates a memory barrier.

    For details, see this comparison (with discussion) of volatile to synchronized.

提交回复
热议问题