Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile variable much more efficient than plain synchronization

I've been told that the use of a volatile variable is much more efficient than using a synchronized block whenever using it (read or write).

Up until Java 1.4 I can see why (because then threads didn't have to flush and refresh all accessible memory).

But since Java 1.5, the only difference I see between using volatile variable and a synchronized block - is the lock acquiring mechanism.

Is acquiring the lock really that expensive? And if so, why is that?

like image 417
user1028741 Avatar asked Nov 02 '22 05:11

user1028741


1 Answers

The "expense" is because of it reading from memory every time, instead of possibly using the memory caches. It is not a lot, at least on x86 machines.

like image 128
crnlx Avatar answered Nov 15 '22 04:11

crnlx