当前位置:网站首页>Foundation of JUC concurrent programming (8) -- read write lock
Foundation of JUC concurrent programming (8) -- read write lock
2022-07-24 06:04:00 【aMythhhhh】
Read-write lock ( a key )
Pessimistic lock and optimistic lock
Pessimistic locks do not support concurrent operations , Efficiency is very low .
Optimistic locking is achieved by adding a version number to the operation resource , Multiple threads can operate at the same time , Who submits first , Version number update , Subsequent threads cannot commit .
Table locks 、 Row lock
When the operation resource is a data table , Table lock directly locks a table , Even if only one row of data is operated .
Row lock locks one row , Other lines can be operated by other threads , However, the row lock may be deadlocked .
Read the lock 、 Write lock
Read the lock : Shared lock , There's a deadlock
Write lock : An exclusive lock , There's a deadlock
Knowledge supplement : Memory visibility issues
Small example :
/** * Example of memory visibility of variables * * @author star */ public class VolatileExample { /** * main Method as a main thread */ public static void main(String[] args) { MyThread myThread = new MyThread(); // Open thread myThread.start(); // Main thread execution for (; ; ) { if (myThread.isFlag()) { System.out.println(" The main thread accesses flag Variable "); } } } } /** * Child thread class */ class MyThread extends Thread { private boolean flag = false; @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // Change the value of the variable flag = true; System.out.println("flag = " + flag); } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } }The console never outputs The main thread accesses flag Variable this sentence , Because the main thread reads flag The value is false, But in MyThread In the thread , It is clear that flag The value is set to true, Why can't I read it ? This involves Java Knowledge of memory models , Memory visibility is involved .
Java Memory model , abbreviation JMM, yes Java Virtual machine defined , It is an underlying model mechanism of concurrent programming .
In general JMM The abstract relationship between thread and main memory is defined : Shared variables between threads are stored in Main memory in , Each thread has a private Local memory , The thread is stored in local memory to read / Write Share a copy of the variable .
Maybe the thread changed the copy value in local memory , however JMM Not updated to main memory in time , What causes other threads to get is still the previous value , Or the thread failed to synchronize the latest value in the main memory to the working memory , This will lead to such visibility problems .
Memory visibility It refers to when a thread modifies the value of a variable , Other threads can always know the change of this variable . in other words , If the thread A Modified shared variables V Value , So thread B In the use of V The value of , Can read immediately V The latest value of .
Two operations to ensure memory visibility :
Lock
The principle of locking is, for example, when a thread obtains a lock , Will empty local memory , Then copy the latest shared variable from main memory , Execute code , Refresh the value of shared variables in main memory after execution , Release the lock .
volatile keyword
Use volatile After modifying shared variables , When each thread wants to manipulate a variable, it copies the variable from main memory to local memory as a copy , When the thread operates a copy of the variable and writes it back to main memory , Will pass CPU Bus sniffer mechanism Tell other threads that the copy of the variable has expired , Need to read from main memory again .
volatile It ensures the visibility of different threads to shared variable operations , In other words, a thread has modified volatile Decorated variable , When the modified variable is written back to main memory , Other threads can see the latest value immediately .
The use of read-write lock is , When the writing thread is not finished , There may be threads reading , So add a write lock , Release the lock after writing , Then you can read , Plus read lock , After reading it, you can continue to write it .
At this time, someone will ask , Then this lock and volatile What's the difference between keywords , Don't you make the shared variables visible to other threads immediately when they are updated ?
My understanding is that ,volatile Just let the working memory and main memory be updated immediately after the shared variables are updated , But before that, the reading thread may read first , So you need a lock , If there is no volatile Even if you finish writing , Maybe what you read is not the updated value .
The evolution of read-write locks :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dEEBhwgM-1657634160743)(C:\Users\aMyth\AppData\Roaming\Typora\typora-user-images\image-20220706211556728.png)]](/img/b2/5173149c627366c0630af888e0ad45.png)
Degradation of read-write lock
Demote write lock to read lock
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-p5wYmizU-1657634160745)(C:\Users\aMyth\AppData\Roaming\Typora\typora-user-images\image-20220706211835744.png)]](/img/45/3332edda8361551d9db07523dad3d6.png)
Blocking queues
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-iiIEdopo-1657634160759)(C:\Users\aMyth\AppData\Roaming\Typora\typora-user-images\image-20220706214115214.png)]](/img/14/f1e79ce9173a1a3afb5ecec5161b0a.png)
Threads 1 Put elements in the queue , Threads 2 Take elements from it
The queue is full Then the thread is blocked , Get thread blocking when empty
Its advantage is that the thread operation of this queue is fully automatic , Don't worry about yourself when you need to block and wake up
Blocking queue classification
ArrayBlockingQueue
Bounded blocking queue with array structure
LinkedBlockingQueue
The list structure consists of ( The default size is integer.MAX_VALUE) Blocking queues
DelayQueue
The use of priority queue to achieve unbounded delay blocking queue
The core approach

边栏推荐
- Accessing a one-dimensional array with a pointer
- 单播、组播、广播、工具开发、QT Udp通讯协议开发简介及开发工具源码
- MySQL download and installation environment settings
- [MYCAT] MYCAT configuration file
- tensorflow和pytorch框架的安装以及cuda踩坑记录
- QT drawing exception using pure code
- Typora installation package in November 2021, the last free version of the installation package to download v13.6.1
- Target detection tagged data enhancement code
- The kernel apps to have died. it will restart automatically
- day-7 jvm完结
猜你喜欢

列表写入txt直接去除中间的逗号

Statistical learning methods (2nd Edition) Li Hang Chapter 22 summary of unsupervised learning methods mind mapping notes

Answers and analysis of some after-school exercises in signals and systems (Wujing)
![[deep learning] handwritten neural network model preservation](/img/4a/27031f29598564cf585b3af20fe27b.png)
[deep learning] handwritten neural network model preservation

day-7 jvm完结

AD1256

"Statistical learning methods (2nd Edition)" Li Hang Chapter 17 latent semantic analysis LSA LSI mind mapping notes and after-school exercise answers (detailed steps) Chapter 17

day3-jvm+排序总结

Could not load library cudnn_ cnn_ infer64_ 8.dll. Error code 126Please make sure cudnn_ cnn_ infer64_ eight
![[activiti] process variables](/img/5e/34077833f6eb997e64f186d4773e89.png)
[activiti] process variables
随机推荐
信号与系统:希尔伯特变换
"Statistical learning methods (2nd Edition)" Li Hang Chapter 17 latent semantic analysis LSA LSI mind mapping notes and after-school exercise answers (detailed steps) Chapter 17
树莓派大用处,利用校园网搭建一个校园局域网站
Numpy cheatsheet
Signals and systems: Hilbert transform
用指针访问二维数组
Better CV link collection (dynamic update)
day3-jvm+排序总结
IoTP2PGate 两台物联网设备点对点通信快速实现方案
原生js放大镜效果
Common features of ES6
列表写入txt直接去除中间的逗号
jupyter notebook一直自动重启(The kernel appears to have died. It will restart automatically.)
PDF Text merge
"Statistical learning methods (2nd Edition)" Li Hang Chapter 16 principal component analysis PCA mind map notes and after-school exercise answers (detailed steps) PCA matrix singular value Chapter 16
顺序栈 C语言 进栈 出栈 遍历
"Statistical learning methods (2nd Edition)" Li Hang Chapter 13 introduction to unsupervised learning mind map notes
day4-jvm
STM32 DSP库MDK VC5\VC6编译错误: 256, (const float64_t *)twiddleCoefF64_256, armBitRevIndexTableF64_256,
Native JS magnifying glass effect