Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java volatile modifier and synchronized blocks

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

like image 698
Chris B Avatar asked Jul 09 '10 17:07

Chris B


People also ask

Do I need volatile in synchronized block?

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..

Should I use volatile with synchronized?

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.

What is the difference between synchronized and volatile?

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.


3 Answers

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

like image 105
Yann Ramin Avatar answered Sep 18 '22 06:09

Yann Ramin


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.

like image 38
Reed Copsey Avatar answered Sep 21 '22 06:09

Reed Copsey


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.

like image 23
Karmastan Avatar answered Sep 22 '22 06:09

Karmastan