当前位置:网站首页>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

边栏推荐
- day5-jvm
- Bat batch script, running multiple files at the same time, batch commands executed in sequence, and xshell script.
- JUC并发编程基础(6)--Lock锁
- Raspberry pie is of great use. Use the campus network to build a campus local website
- [activiti] process variables
- [MYCAT] MYCAT configuration file
- Qt新手入门级 计算器加、减、乘、除、应用
- JUC并发编程基础(9)--线程池
- vsual studio 2013环境 Udp组播
- js星星打分效果
猜你喜欢

day6-jvm

【树莓派4B】七、远程登录树莓派的方法总结XShell,PuTTY,vncServer,Xrdp

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

Delete the weight of the head part of the classification network pre training weight and modify the weight name

The problem that the user name and password are automatically filled in when Google / Firefox manages the background new account
![[MYCAT] related concepts of MYCAT](/img/44/99d413d47828252267b5242c64960b.png)
[MYCAT] related concepts of MYCAT

字符串方法以及实例

"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

论文阅读-Endmember-Guided Unmixing Network (EGU-Net) 端元指导型高光谱解混网络

Machine learning (Zhou Zhihua) Chapter 4 notes on learning experience of decision tree
随机推荐
Conversion of world coordinate system, camera coordinate system and image coordinate system
Typora installation package in November 2021, the last free version of the installation package to download v13.6.1
Raspberry pie is of great use. Use the campus network to build a campus local website
Qt 使用纯代码画图异常
STM32 standard peripheral Library (Standard Library) official website download method, with 2021 latest standard firmware library download link
Vscode multiline comments always expand automatically
Machine learning (zhouzhihua) Chapter 1 Introduction notes learning experience
AD1256
CRC-16 Modbus代码
【USB Host】STM32H7 CubeMX移植带FreeRTOS的USB Host读取U盘,USBH_Process_OS卡死问题,有个值为0xA5A5A5A5
树莓派大用处,利用校园网搭建一个校园局域网站
C language linked list (create, traverse, release, find, delete, insert a node, sort, reverse order)
QT drawing exception using pure code
MySQL download and installation environment settings
Test whether the label and data set correspond after data enhancement
顺序栈 C语言 进栈 出栈 遍历
JS star scoring effect
[MYCAT] related concepts of MYCAT
Openwrt quick configuration Samba
Chapter IV decision tree summary