Java volatile modifier and synchronized blocks
Asked Answered
H

3

17

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

Hesperidium answered 9/7, 2010 at 17:9 Comment(2)
You may also be interested in this question: #3103704Fashion
No. Refer to this relaled SE question: #3520164Ignaz
H
15

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

Hunk answered 9/7, 2010 at 17:13 Comment(0)
C
5

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.

Campground answered 9/7, 2010 at 17:12 Comment(0)
E
2

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.

Eyeopening answered 9/7, 2010 at 17:18 Comment(3)
To be pedantic, synchronizing in other languages does not imply consistent memory - the value may be cached in a register or local memory, and even though the access is synchronized, it may not be atomic/consistent. However, in Java, synchronized turns on an automatic volatile.Hunk
To be equally pedantic, the other languages you're probably thinking of (C/C++) don't have an intrinsic notion of synchronizing threads, or even a synchronized keyword; you have to construct something similar out mutexes. There you're right: there is no runtime to manage memory consistency for you. Those languages don't even specify any semantics for concurrent memory accesses! Thankfully Java is nice and just does what you expect it to do.Eyeopening
@YannRamin As in, the variable you synchronize on is effectively volatile for the purpose of modifications to it made within that synchronized block? Not sure if I interpreted you correctly, but I can't find a description of that effect elsewhere.Podgy

© 2022 - 2024 — McMap. All rights reserved.