Java volatile modifier and synchronized blocks

前端 未结 3 819
忘了有多久
忘了有多久 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 13:09

    You do not need to use volatile inside of synchronized, synchronized already guarantees the correct behavior for local caching of variables when used consistently (on every access).

    volatile works on primitive values, and can be a nice shortcut for atomic accesses to a primitive type. Note that the behavior of volatile has changed in JDK 5 from 1.4.

    More information can be found here

提交回复
热议问题