Does a variable that is accessed by multiple threads, but only inside synchronized blocks, need the volatile modifier? If not, why?
You can do synchronization without using synchronized block. It's not a necessary to use volatile variable in it... volatile updates the one variable from main memory..and synchronized Update all shared variables that have been accessed from main memory..
When to use Volatile over Synchronized modifiers can be summed up into this: Use Volatile when you variables are going to get read by multiple threads, but written to by only one thread. Use Synchronized when your variables will get read and written to by multiple threads.
Synchronized is applicable only on blocks or methods. Volatile is applicable to variables only. The synchronized modifier is used to implement a lock-based concurrent algorithm, i.e it suffers from the limitation of locking. Whereas Volatile gives the power to implement a non-blocking algorithm that is more scalable.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With