当前位置:网站首页>The interviewer asked the thread safe list, and I'm not afraid after reading it!
The interviewer asked the thread safe list, and I'm not afraid after reading it!
2022-07-27 23:55:00 【Xi. Technical chopping】
since ArrayList It's not thread safe , How to ensure its thread safety ? Or an alternative ?
To look down , See how I crush him !
Most people will blurt out : use Vector, This will only make the interviewer despise ! except Vector, Can you do anything else ?
You have to say that at least :
java.util.Collections.SynchronizedList
It can take everything List Interface implementation class into thread safe List, Than Vector Better scalability and compatibility ,SynchronizedList The construction method of is as follows :
final List<E> list;
SynchronizedList(List<E> list) {
super(list);
this.list = list;
}
SynchronizedList Part of the method source code is as follows :
public E get(int index) {
synchronized (mutex) {return list.get(index);}
}
public E set(int index, E element) {
synchronized (mutex) {return list.set(index, element);}
}
public void add(int index, E element) {
synchronized (mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized (mutex) {return list.remove(index);}
}
It is a pity that , All of its methods are synchronized object locks , and Vector equally , It's not the best performance . Even if you can say that , The interviewer will continue to ask , For example, in the case of reading more and writing less ,SynchronizedList The performance of this set is very poor , Is there a more appropriate solution ?
Introduce two concurrent collection classes in the parallel contract :
java.util.concurrent.CopyOnWriteArrayList
java.util.concurrent.CopyOnWriteArraySet
CopyOnWrite There are only two collection classes ,Java 1.5 Start to join , You have to be able to say both to convince the interviewer .
CopyOnWriteArrayList
CopyOnWrite( abbreviation :COW): Copy and write , When you add elements , First put the original List Make a copy of the list , Add new elements .
Let's take a look at its add Method source code :
public boolean add(E e) {
// Lock
final ReentrantLock lock = this.lock;
lock.lock();
try {
// Get the original collection
Object[] elements = getArray();
int len = elements.length;
// Copy a new collection
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
// Replace the original collection with a new one
setArray(newElements);
return true;
} finally {
// Release the lock
lock.unlock();
}
}
When adding elements , Lock first , Then copy and replace , Finally release the lock .
Let's take a look at it get Method source code :
private E get(Object[] a, int index) {
return (E) a[index];
}
public E get(int index) {
return get(getArray(), index);
}
You can see , Get element is not locked .
The advantage of this is , In high concurrency , There is no need to lock when reading elements , Lock when writing data , Greatly improves read performance .
CopyOnWriteArraySet
CopyOnWriteArraySet The logic is simpler , Is the use of CopyOnWriteArrayList Of addIfAbsent Methods come and go , When adding elements, judge whether the object already exists , It's added to the collection when it doesn't exist .
/**
* Appends the element, if not present.
*
* @param e element to be added to this list, if absent
* @return {@code true} if the element was added
*/
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
These two concurrent collections , It's tough , But it's only suitable for reading more and writing less , If you write more and read less , There's no point in using this , Because every write operation has to copy the collective memory , High performance overhead , If the set is large , It's easy to cause memory overflow .
summary
Next time the interviewer asks you thread safe List, You can start your Vector > SynchronizedList > CopyOnWriteArrayList In this order , That's how I feel , It can also reflect your mastery of knowledge points .
Have you got anything after watching it ? The next interview should be able to kill the interviewer !

边栏推荐
- Redefine analysis - release of eventbridge real-time event analysis platform
- 【12月海口】2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
- 资深如何确定软件测试结束的标准
- 2022 International Conference on civil, building and Environmental Engineering (iccaee 2022)
- [RoarCTF2019]babyRSA威尔逊定理
- Flutter pull_to_refresh-1.6.0/lib/src/internals/slivers.dart:164:13: Error: Method not found: ‘descr
- 五子棋人机对战实现
- JS array copy speed test 220320
- C # delegate usage -- console project, which implements events through delegation
- NDK series (6): let's talk about the way and time to register JNI functions
猜你喜欢

Monologue of a software Investor: why don't I pursue fast-growing companies

给网站套上Cloudflare(以腾讯云为例)

org.junit.runners.model.InvalidTestClassError: Invalid test class ‘com.zhj.esdemo.MysqlTests‘: 1.

为什么 Redis 集群要使用反向代理? 看这篇就明白了

Key points of data management

Character stream learning 14.3

2022 summer vacation daily question (5)

2022 International Conference on civil, building and Environmental Engineering (iccaee 2022)

基于原生js实现今日新闻网站
![[NCTF2019]babyRSA1](/img/c1/52e79b6e40390374d48783725311ba.gif)
[NCTF2019]babyRSA1
随机推荐
TFRecord的Shuffle、划分和读取
Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further
【C语言】通讯录(动态版本)
Decrypt the secret of 90% reduction in oom crash~
NDK 系列(6):说一下注册 JNI 函数的方式和时机
[NPUCTF2020]EzRSA
[RoarCTF2019]RSA
Smartrefresh nested multiple recycleview sliding conflicts and incomplete layout display
资深如何确定软件测试结束的标准
BUUCTF-RSA4
Features of hardwired controller:
Master data management theory and Practice
Current situation and future of Nb IOT industry: cross the threshold of 100million shipments and rush to 5g connection!
尚硅谷尚品项目汇笔记(一)
29.学习Highcharts 使用百分比的堆叠柱形图
Arm32 for remote debugging
【JS 逆向百例】某公共资源交易网,公告 URL 参数逆向分析
Your list is too laggy? These four optimizations can make your list silky smooth
BUUCTF-RSA
JUC工具包学习