The visibility of synchronization blocks is determined by “ Execute on a variable unlock Before, This variable must be synchronized back to main memory ( perform store、write operation )” This rule gets. except volatile Besides keywords ,Java There are also two keywords that allow visibility, They are synchronized and final.
![operation java operation java](https://scanftree.com/images/java/armstrong-number-java.png)
Visibility is the value when a thread changes the value of a shared variable, Other threads are immediately aware of the change.
Operation java code#
These two bytecode instructions reflect Java In the code is the synchronization block -synchronized keyword, So in synchronized Operations between blocks are also atomic. If the application scenario needs a wider range of atomicity guarantees ,Java The memory model also provides lock and unlock Operations to meet this need, Although the virtual machine does not lock and unlock Operation is directly open to users, But it provides a higher level of bytecode instructions monitorenter and monitorexit To implicitly use these two operations. Variable data transfer between threads must pass through main memory, Threads 、 The relationship between main memory and working memory is shown in the figure below :įrom Java Memory model to directly ensure the atomicity of variable operation packages, including read、load、assign、use、store and write These six, We generally believe that, Access to basic data types 、 Reading and writing are atomic. ) Must be done in working memory, Can't write directly into main memory. Each thread has its own working memory ( Working memory, Similar to processor cache ), The thread's working memory stores the main memory of the variables used by the thread, All actions of the thread on variables ( Read 、 Assignment etc. Java Memory mode stores all variables in the main memory ( The main memory here is like the main memory in physical hardware, The two can be similar, But actually, This is just part of the virtual machine memory ). To improve performance, Java The memory does not interact with the memory model or the memory execution engine, There are no restrictions on the instructions modified by the technical compiler. The variables here are different from Java Variables in programming, Include instance fields, Static field, And the elements that make up the array object, But it does not contain local variables and method parameters.
![operation java operation java](https://images5.alphacoders.com/545/545208.jpg)
Java The primary goal of memory model is to set an access rule for various variables in the program, That is to store variables in the virtual machine, And extracting variables from memory.