7. Read write lock of Java lock

Why is the algorithm so difficult 2021-02-23 18:30:19
read write lock java lock


Concept

An exclusive lock : This lock can only be held by one thread lock at a time (ReetrantLock and Synchronized All exclusive locks )

Shared lock : The lock can be held by multiple threads

Yes ReentrantReadWriteLock for , Its read lock is sharing , Write lock is exclusive . When I write, I write by myself , But it can be read by many people at the same time .

Why write lock and read lock

So we use ReentrantLock When creating locks , Is an exclusive lock , That is to say, only one thread can access it at a time . But there's a read-write separation scenario , I want to read at the same time , Because read locks don't cause data inconsistency , So it can be shared by many people .

There is no problem for multiple threads to read a resource class at the same time , If a thread wants to write shared memory , No other thread should read or write to the resource .

Code implementation

  • Implementation of a read-write cache operation , Suppose there is no lock at the beginning , What happens

Simulate it first HashMap Of put and get Method :

 public class MyCache {
 ​
 private volatile Map<String,Object> map = new HashMap<>();
 
 // Write method
 public void put(String key,Object value) throws InterruptedException {
  System.out.println(" Threads "+ Thread.currentThread().getName() +" Are written to the :" + key);
 
  TimeUnit.MILLISECONDS.sleep(300); // Simulate network congestion , Delay 0.3s
  map.put(key,value); // Write elements
 
  System.out.println(" Threads "+ Thread.currentThread().getName() +" Write successfully ");
 }
 
 // Read method
 public void get(String key) throws InterruptedException {
  System.out.println(" Threads "+ Thread.currentThread().getName() +" Reading :");
 
  TimeUnit.MILLISECONDS.sleep(300); // Simulate network congestion , Delay 0.3s
  Object value = map.get(key); // Read elements
 
  System.out.println(" Threads "+ Thread.currentThread().getName() +" Read complete :" + value );
 }
 }

test :

 public static void main(String[] args) {
 ​
  MyCache myCache = new MyCache();
 ​
  // establish 5 Threads write to the cache
  for (int i = 0; i < 5; i++) {
  final int tempInt = i; //lambda The variable inside the expression must be final
 ​
  new Thread(() -> {
  myCache.put(tempInt + "", tempInt + "");
  }, " Threads " + i).start();
  }
 
  // establish 5 Thread read cache
  for (int i = 0; i < 5; i++) {
  final int tempInt = i; //lambda The variable inside the expression must be final
 ​
  new Thread(() -> {
  myCache.get(tempInt + "");
  }, " Threads " + i).start();
  }
 ​
 }

Running result display :

resolvent

The above code is not locked , This will cause the thread to be in progress Write operation When , Frequently interrupted by other threads , So there is no atomicity , Now , We need to use read-write lock to solve the problem .

Create a read-write lock :

 private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
 ​
 // It's a lock that integrates reading and writing , In use , Need to transform

When we're writing , It needs to be converted to a write lock :

 // Create a write lock
 rwLock.writeLock().lock();
 ​
 // Write lock Release
 rwLock.writeLock().unlock();

When you're reading , After converting to read lock

 // Create a read lock
 rwLock.readLock().lock();
 ​
 // Read the lock Release
 rwLock.readLock().unlock();

The difference between read lock and write lock is , Write lock can only be entered by one thread at a time , Perform write operations , Read lock means that multiple threads can enter at the same time , To read .

We will take MyCache Class put Method Add a write lock to the front of the , Finally release the lock .get Method Add a read lock at the front of the , Finally release the lock .

Finally, let's look at the running results after adding read-write lock :

From the running results, we can see that , Write operations are performed one thread at a time , And there's no interruption in the middle , And the read operation , At the same time 5 Threads in , And then concurrent read operations .

版权声明
本文为[Why is the algorithm so difficult]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223182957051x.html

  1. JAVA的函数式接口
  2. JAVA里的元祖类
  3. JQuery Gantt package to create a new ASP.NET project
  4. Binary conversion of Unicode code (Java)
  5. The functional interface of Java
  6. Yuanzu class in Java
  7. Java中的CPU占用高和内存占用高的问题排查
  8. HashMap连环问你能答出几道?
  9. IntelliJ IDEA 还能画思维导图,果然最强 IDE!
  10. java中的反射和代理
  11. Troubleshooting of high CPU and memory usage in Java
  12. How many questions can you answer?
  13. IntelliJ idea can also draw mind maps. It's really the strongest ide!
  14. Reflection and proxy in Java
  15. Java中的CPU占用高和内存占用高的问题排查
  16. Linux OOM(out of memory)
  17. mysql 自定义函数因参数名称报错
  18. Troubleshooting of high CPU and memory usage in Java
  19. Linux OOM(out of memory)
  20. MySQL user defined function error due to parameter name
  21. echarts-gl 3D 地图柱状图可视化GDP
  22. Visualization of histogram of ecarts GL 3D map
  23. 金三银四如何应对Redis面试,一文深入Redis实战实践!
  24. 阿里资深架构师定制金三银四面试整理出来的一份Java核心知识点.pdf
  25. 为什么Java开发工程师工资高,却很多人想转行?
  26. How to deal with the interview of redis!
  27. Ali senior architect customizes a Java core knowledge point sorted out in the interview of golden, silver and four.pdf
  28. Why do java development engineers have high salaries, but many people want to change careers?
  29. 用注解开发SpringMVC
  30. Developing spring MVC with annotations
  31. 编译redis报错/deps/hiredis/libhiredis.a解决
  32. Compile redis report error / DEPs / hirredis / libhirredis. A solution
  33. 用注解开发SpringMVC
  34. Developing spring MVC with annotations
  35. Spring学习笔记-01
  36. Centos安装和卸载docker
  37. Spring learning notes-01
  38. Installing and uninstalling docker in CentOS
  39. Java基础-异常
  40. Java基础-反射
  41. Java基础-继承
  42. k8s部署 (进行中)
  43. Hive-常见调优方式 && 两个面试sql
  44. 死磕Spring之IoC篇 - BeanDefinition 的加载阶段(XML 文件)
  45. Java basics exception
  46. Java Basics - Reflection
  47. Java Basics - inheritance
  48. K8s deployment (in progress)
  49. Hive common tuning methods & two interview SQL
  50. The loading phase of beandefinition (XML file)
  51. 死磕Spring之IoC篇 - BeanDefinition 的加载阶段(XML 文件)
  52. Hive-常见调优方式 && 两个面试sql
  53. The loading phase of beandefinition (XML file)
  54. Hive common tuning methods & two interview SQL
  55. iconv文件编码转换由windows文件放到linux下
  56. The code conversion of iconv file is put into Linux by windows file
  57. SpringBoot2+intellij IDEA开发前环境准备
  58. Preparation of pre development environment for springboot2 + IntelliJ idea
  59. Docker私有仓库部署
  60. Docker private warehouse deployment