Does Java volatile prevent write caching or forced caching?

I am trying to understand the Java keyword volatilein relation to spelling for a volatile atomic variable in a multi-threaded program with processor caches.

I have read several guides and the Java language specification, in particular section 17.4.5 on “happens before ordering” . I understand that when a thread writes a new value to a volatile variable, the updated value should be visible to other threads reading this variable. For me, this semantics can be implemented in one of two ways:

  • Themes can cache a volatile variable in the CPU cache, but writing to the variable in the cache should be immediately deleted to main memory. In other words, write-through cache .

  • Threads can never cache a mutable variable and must read and write such variables in main memory.

Approach 1 is mentioned in this tutorial ( http://tutorials.jenkov.com ), which states:

By declaring a volatile counter variable, all records on the counter variable will immediately be returned to main memory.

Approach 2 is mentioned in the Stackoverflow question “ Variable Variable in Java ” as well as this tutorial , which says:

-: " "

, Java?

, Stackoverflow, :

Java

Java-volatile -

Java

+4
3

- , . , , , , , - - . , , , .

, , , , , - . , .

+4

Java , volatile, , /.

Java , / ( ).


, Java; / L1 . , Java , .

volatile Java, - / . :

  • , , ( , , , L1).

  • / ( , , / ).

Java,

//on one thread
counter += 1; //normal int field
flag = true; //flag is volatile

//on another thread
if (flag) foo(counter); //will see the incremented value

, flag true . Thread # 2 , . , counter += 1 , . , flag == true, counter .


, ;

  • ( "/ " ).

  • / - / .

+3

: volatile .

-2, , , .

-: " "

javabeat :

, . , , . , .

javarevisited :

volatile Java , volatile , Thread.

SE:

Java

( ) ,

volatile, , ( ) , CPU

volatile local Thread cache, Thread cache. , java .

0

All Articles