After reading the copyonwritearraylist, I implemented a copyonwritehashmap

Java Finance 2021-01-05 17:11:14
reading copyonwritearraylist implemented copyonwritehashmap


 Insert picture description here

introduction

interviewer : You look familiar, young man , Did you come here for an interview last year .<br/>
Second fat : ah , No, this is my first time here .<br/>
interviewer : That's ok , Let's start today's interview , Let's start with something simple ,java What do you know about the containers inside , Tell me about it .<br/>
Second fat : well ,java The common containers inside are ArrayList( Thread is not safe )、HashMap( Thread is not safe )、HashSet( Thread is not safe ),ConcurrentHashMap( Thread safety ).<br/>
interviewer : ArrayList Since thread is not safe, is there any thread safe ArrayList Column ?<br/>
Second fat : This ... It seems that I have asked about the blind spot of knowledge .<br/>
interviewer : That's where we're going for today's interview , I have another meeting later , If there is any further notice, the personnel will contact you .<br/>
The above stories are purely fictional. If they are similar, please focus on this article .

What is? COW

stay java When it comes to collection containers, the first thing we usually think of is HashMapArrayListHasHSet These containers are also the most commonly used in development .
These are all non thread safe , If we have a specific business that needs to use thread safe container Columns ,

  • HashMap It can be used ConcurrentHashMap Instead of .
  • ArrayList have access to Collections.synchronizedList() Method (list Every method uses synchronized modification ) Or use Vector( Now it's basically not used , Every method uses synchronized modification )

Or use CopyOnWriteArrayList replace .

  • HasHSet have access to Collections.synchronizedSet Or use CopyOnWriteArraySet Instead of .(CopyOnWriteArraySet Why not call CopyOnWriteHashSet because CopyOnWriteArraySet The bottom layer uses CopyOnWriteArrayList To achieve )

We can see CopyOnWriteArrayList Many times in a thread safe container .
First, let's look at what CopyOnWriteCopy-On-Write abbreviation COW, It's an optimization strategy for programming .

CopyOnWrite Container is the container copied on write . The popular understanding is that when we add elements to a container , Do not add... Directly to the current container , Instead, first, I'll do the current container Copy, Copy out a new container , Then add elements to the new container , After adding elements , Then point the reference of the original container to the new container . The advantage of this is that we can treat CopyOnWrite The container reads concurrently , Without lock , Because the current container will not add any elements . therefore CopyOnWrite Container is also an idea of separation of reading and writing , Read and write in different containers .

Why introduce COW

prevent ConcurrentModificationException abnormal

stay java If we use the wrong circular posture to traverse List When , If you modify and throw while traversing java.util.ConcurrentModificationException FALSE .
If the ArrayList Loop traversal is not very familiar, you can suggest to see this article 《ArrayList Have you mastered all the delete postures of 》

 List<String> list = new ArrayList<>();
list.add(" Zhang San ");
list.add("java Finance ");
list.add("javajr.cn");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String content = iterator.next();
if(" Zhang San ".equals(content)) {
list.remove(content);
}
}

This chestnut on top is going to happen java.util.ConcurrentModificationException Anomalous , If you put ArrayList Change it to CopyOnWriteArrayList There will be no abnormality .

Thread safe containers

Let's look at the next chestnut, a thread to List Add data , A thread loop list Reading data .

 List<String> list = new ArrayList<>();
list.add(" Zhang San ");
list.add("java Finance ");
list.add("javajr.cn");
Thread t = new Thread(new Runnable() {
int count = 0;
@Override
public void run() {
while (true) {
list.add(count++ + "");
}
}
});
t.start();
Thread.sleep(10000);
for (String s : list) {
System.out.println(s);
}

What happens when we run the above code ConcurrentModificationException abnormal , If you put ArrayList Instead of CopyOnWriteArrayList It's all right .

CopyOnWriteArrayList The implementation of the

From the two chestnuts above, we can see that CopyOnWriteArrayList It's thread safe , Now let's take a look CopyOnWriteArrayList How to realize thread safety .

public class CopyOnWriteArrayList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8673264195747942595L;
/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();
/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;

From the source code we can see that CopyOnWriteArrayList This sum ArrayList The underlying implementation is through a Object The array of , It's just CopyOnWriteArrayList The array of is through volatile To decorate , Why volatile You can take a look at 《Java Of synchronized Can I prevent instruction reordering ?》
There are also new ReentrantLock.

add Method :

 public boolean add(E e) {
// Get the lock first
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
// Copy a new array
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
// Put the values of the new array To the original array
setArray(newElements);
return true;
} finally {
// Release the lock
lock.unlock();
}
}

The above source code is relatively simple , There are a few points that need a little attention

  • When you add data, it's through ReentrantLock To lock ( stay jdk11 I used synchronized To replace ReentrantLock) Ensure that when multithreading writes, only one thread copies the array , Otherwise, there will be multiple copies of copied data in the memory , Leading to data confusion .
  • Arrays are passed through volatile Embellished , according to volatile Of happens-before The rules , The modification of the array reference by the write thread can be immediately visible to the read thread .
  • Copy while writing to ensure that read and write operations are carried out in two different data containers .

Realize one by yourself COW Containers

Again Java Two uses are provided in the contract CopyOnWrite Concurrent containers implemented by mechanism , They are CopyOnWriteArrayList and CopyOnWriteArraySet, But it didn't CopyOnWriteHashMap We can follow his ideas to achieve a CopyOnWriteHashMap

public class CopyOnWriteHashMap<K, V> implements Map<K, V>, Cloneable {
final transient ReentrantLock lock = new ReentrantLock();
private volatile Map<K, V> map;
public CopyOnWriteHashMap() {
map = new HashMap<>();
}
@Override
public V put(K key, V value) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Map<K, V> newMap = new HashMap<K, V>(map);
V val = newMap.put(key, value);
map = newMap;
return val;
} finally {
lock.unlock();
}
}
@Override
public V get(Object key) {
return map.get(key);
}
@Override
public V remove(Object key) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Map<K, V> newMap = new HashMap<K, V>(map);
if (!newMap.containsKey(key)) {
return null;
}
V v = newMap.get(key);
newMap.remove(key);
map = newMap;
return v;
}finally {
lock.unlock();
}
}

So we've implemented a simple CopyOnWriteHashMap, only add、remove、get Methods the rest of the methods can be implemented by themselves , It involves locking as long as the data changes , Read without lock .

Application scenarios

CopyOnWrite The concurrency container is suitable for concurrency scenarios with more reads and less writes , Like the black and white list 、 National City and other basic data cache 、 System configuration, etc . These are basically initialized once when the project starts , The frequency of change is very low . If this scenario of reading more and writing less adopts Vector,Collections These ways of packing are unreasonable , Because although multiple read threads read data from the same data container , But the read thread does not modify the data of the data container , So there's no need to read and lock .

CopyOnWrite shortcoming

CopyOnWriteArrayList Although it's a thread safe version of ArrayList, But every time it changes the data, it copies a copy of the data , therefore CopyOnWriteArrayList It is only suitable for reading more and writing less or reading without lock . If we use it in real business CopyOnWriteArrayList, It must be because the scene is suitable, not to show off .

Memory usage problem

because CopyOnWrite There are two array objects in memory each time a write operation is performed , If this array object takes up a large amount of memory , If you write frequently, it will cause frequent Yong GC and Full GC.

Data consistency issues

CopyOnWrite The container can only guarantee the final consistency of the data , There is no guarantee of real-time consistency of data . The read thread may not read the newly modified data immediately , Because the modification takes place on the replica . But the final modification completes and updates the container, so this is the final consistency .

CopyOnWriteArrayList and Collections.synchronizedList()

A simple test CopyOnWriteArrayList and Collections.synchronizedList() The discovery of reading and writing :

  • When writing with high concurrency CopyOnWriteArray Compared with synchronization Collections.synchronizedList A hundred times slower
  • At high concurrent read performance CopyOnWriteArray Compared with synchronization Collections.synchronizedList Dozens of times faster .
  • When writing with high concurrency ,CopyOnWriteArrayList Why is it so slow ? Because every time add when , Use both Arrays.copyOf Create a new array , frequent add When the memory request is released, the performance consumption is large .
  • High concurrency reading CopyOnWriteArray unlocked ,Collections.synchronizedList There is a lock, so the efficiency of reading is relatively low .

summary

choice CopyOnWriteArrayList When reading, it must be much more than writing . If reading and writing are almost the same, it is recommended to choose Collections.synchronizedList.

end

  • Because of my lack of talent and learning , It's hard to avoid mistakes , If you find something wrong , I'd like to leave a message and point it out to me , I'll fix it .
  • If you think the article is good , Your forwarding 、 Share 、 appreciate 、 give the thumbs-up 、 The message is the biggest encouragement to me .
  • Thank you for reading , Thank you for your attention .

 Insert picture description here
The giant picked apples on his shoulders
http://ifeve.com/java-copy-on...

版权声明
本文为[Java Finance]所创,转载请带上原文链接,感谢
https://javamana.com/2020/12/20201231080158440c.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云