The purpose / benefits of volatiles

What is the situation when you use a keyword volatile? And more importantly: how is the program profitable?

From what I already read and know: it volatileshould be used for variables accessed by different threads, because they are read a little faster than non-volatile ones. If so, shouldn't there be a keyword for enforcing the opposite?

Or are they actually synchronized between all threads? How ordinary variables are not?

I have a lot of multithreaded code and I want to optimize it a bit. Of course, I do not hope for huge performance (I have no problems with this atm), but I always try to make my code better. And I'm a little confused by this keyword.

+4
source share
5 answers

When a multi-threaded program is running, and there is some common variable that is not declared as volatile, then these threads create a local copy of the variable and work with the local copy instead. Thus, changes to the variable are not reflected. This local copy is created because access to cached memory is much faster compared to accessing variables from main memory.

When you declare a variable as volatile, it tells the program NOT to create any local copy of the variable and use the variable directly from main memory.

volatile, , , , , .

, volatile , volatile, , . , , .

+7

Volatile , , .

.

Java

+2

volatile , , . , - , . , , , , . , , , , . volatile .

+2

wiki

, C, ++, # Java, , volatile, , / . , volatile , , , "".

** ^

, , .

+1

volatile . volatile . .

: - volatile Java?

, . . .

, , , , .

+1

Source: https://habr.com/ru/post/1528241/


All Articles