当前位置:网站首页>Volatile and threads
Volatile and threads
2022-06-23 04:39:00 【Bug trendsetter】
volatile keyword
If a variable is in more than one CPU There are caches in ( It usually appears in multithreaded programming ), Then there may be cache inconsistency . To solve cache inconsistency , Generally speaking, there are the following 2 A solution :
By adding... On the bus LOCK# The way of locking
Through cache consistency protocol
this 2 All of them are provided at the hardware level .
i If in the process of executing this code , Issued on the bus LCOK# Lock signal , Then wait until the code is completely executed , other CPU From variables i Where the memory reads variables , Then carry out the corresponding operation . This solves the problem of cache inconsistency .
Cache consistency protocol . The most famous is Intel Of MESI agreement ,MESI The protocol ensures that the copies of shared variables used in each cache are consistent . Its core idea is : When CPU When writing data , If the variable of the operation is found to be a shared variable , In other CPU A copy of the variable also exists in , Signal others CPU Set the cache row of this variable to invalid state , So when other CPU When you need to read this variable , It is found that the cache row of this variable in its own cache is invalid , So it's going to re read from memory .

Java Inter memory interaction
JLS The operation instruction of thread to main memory is defined :lock,unlock,read,load,use,assign,store,write. These behaviors are indecomposable atomic operations , Interdependence in use ,read-load Copy variables from main memory to current working memory ,use-assign Execute the code to change the value of the shared variable ,store-write Refresh main memory with working memory data .
read( Read ): Operates on the main memory variable , Transfers a variable value from main memory to the thread's working memory , For subsequent load The action to use
load( load ): A variable acting on working memory , It is the read The operation places the values of the variables obtained from main memory into a copy of the variables in working memory .
use( Use ): A variable acting on working memory , Passes the value of a variable in working memory to the execution engine , This is done whenever the vm gets a bytecode instruction that requires the value of the variable to be used .
assign( assignment ): A variable acting on working memory , It assigns a value received from the execution engine to a variable in the working memory , This is done whenever the vm receives a bytecode instruction that assigns a value to a variable .
store( Storage ): A variable acting on working memory , Transfers the value of a variable in working memory to main memory , For subsequent write The operation of .
write( write in ): A variable acting on main memory , It is the store Operations are passed from the value of a variable in working memory to the variable in main memory .
Atomicity , visibility , Orderliness
Three features of multithreading .
For visibility ,Java Provides volatile Keywords to ensure visibility .
When a shared variable is volatile When decorating , It ensures that the modified value is immediately updated to main memory , When there are other threads that need to read , It will go to memory to read new values .
And common shared variables don't guarantee visibility , Because after the common shared variable is modified , When it is written to main memory is uncertain , When other threads go to read , At this time, the memory may still be the old value , So there's no guarantee of visibility .
in addition , adopt synchronized and Lock It also ensures visibility ,synchronized and Lock It can guarantee that only one thread can acquire lock and execute synchronization code at the same time , And before releasing the lock, the changes to variables will be refreshed to main memory . So you can guarantee visibility .
The following passage is from 《 In depth understanding of Java virtual machine 》:
“ Observe the addition of volatile Keywords and did not add volatile Keyword generated assembly code found , Join in volatile When a keyword , One more lock Prefix instruction ”
lock The prefix instruction is actually equivalent to a Memory barrier ( It's also a memory fence ), The memory barrier will provide 3 Features :
It ensures that instructions are reordered without putting the instructions behind them in front of the memory barrier , It doesn't put the previous instructions behind the memory barrier ; That is, when the instruction of memory barrier is executed , All the operations before it have been completed ;
It forces changes to the cache to be written to main memory immediately ;
If it's a write operation , It can lead to other CPU The corresponding cache row in is invalid .
Here are a few Java Use in volatile Several scenes of .
State marker quantity
double check Prevent instruction reordering :
Prevent instruction reordering from causing other threads to get uninitialized objects .instance = new Singleton()This sentence , This is not an atomic operation , In fact JVM I've probably done the following 3 thing .But in JVM There are instructions reordering optimizations in the immediate compiler of . That is to say, the order of the second and third steps above is not guaranteed , The final order of execution may be 1-2-3 It could be 1-3-2. If it's the latter , It's in 3 completion of enforcement 、2 Before execution , By thread two , At this time instance Right and wrong null 了 ( But it's not initialized ), So thread two will directly return instance, And then use , Then an error . added volatile No reordering .
to instance Allocate memory
call Singleton To initialize member variables
take instance Object points to the allocated memory space ( Finish this step instance It's just wrong null 了 )
When new When an object , It is also allocated in main memory .
synchronized Key words and volatile The difference between keywords
volatile Keyword is a lightweight implementation of thread synchronization , therefore volatile Performance is definitely better than synchronized Keywords are better . however volatile Keywords can only be used for variables , and synchronized Keywords can modify methods and code blocks .
Multithreaded access volatile Keywords don't block , and synchronized Keywords may block .
volatile Keywords ensure data visibility , But it doesn't guarantee the atomicity of the data .synchronized Keywords both guarantee .
volatile Keyword is mainly used to solve the visibility of variables among multiple threads , and synchronized Keyword solves the synchronization of accessing resources among multiple threads
Remember to point 「 Fabulous 」 and 「 Looking at 」↓
Love you
边栏推荐
- LabVIEW在同一表中同时显示十六进制字符和普通字符
- x64dbg 基本使用技巧
- Halcon知识:binocular_disparity 知识
- Fundamentals of 3D mathematics [16] formulas for uniformly accelerated linear motion
- The spring recruitment in 2022 begins, and a collection of interview questions will help you
- 靜態查找錶和靜態查找錶
- What are the characteristics of SRM supplier management system developed by manufacturing enterprises
- Sessions and Daemons
- x24Cxx系列EEPROM芯片C语言通用读写程序
- Online text filter less than specified length tool
猜你喜欢
![[advanced binary tree] AVLTree - balanced binary search tree](/img/a5/aef68dd489ef5545e5b11ee2d3facc.png)
[advanced binary tree] AVLTree - balanced binary search tree

It supports running in kubernetes, adds multiple connectors, and seatunnel version 2.1.2 is officially released!

C语言刷题随记 —— 自由落体的球

Introduction to deep learning

Pytoch --- use pytoch's pre training model to realize four weather classification problems

Leetcode 1208. 尽可能使字符串相等(终于解决,晚安)

JD cloud distributed database stardb won the "stability practice pioneer" of China Academy of information technology
![3D数学基础[十六] 匀加速直线运动的公式](/img/51/5b05694bbd0f4fd01dd26cf55b22c7.png)
3D数学基础[十六] 匀加速直线运动的公式

摆烂LuoGu刷题记

Cocos学习日记2——脚本和属性
随机推荐
How to ensure application security
【二叉树进阶】AVLTree - 平衡二叉搜索树
【深度学习】深度学习推理框架 TensorRT MNN OpenVINO ONNXRuntime
x64dbg 基本使用技巧
PTA:7-87 集合的模拟实现(类模板)
svg d3. JS generate tree tree view
Can MySQL be used in Linux
The spring recruitment in 2022 begins, and a collection of interview questions will help you
x24Cxx系列EEPROM芯片C语言通用读写程序
PTA:7-67 友元很简单2016final
Inscription of lougu brush
How to use MySQL index well
Halcon glue line detection - template matching, pose transformation, glue width, glue continuity detection
自动化测试常见的面试题
OpenJudge NOI 1.13 51:古代密码
Getting started with tensorflow
Online JSON to CSharp (c) class tool
QT elidedText 只对中文符合起作用,对英文不起作用的问题解决
Flutter series: wrap in flutter
[learn FPGA programming from scratch -40]: Advanced - Design - competition and risk