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

边栏推荐
- C # delegate usage -- console project, which implements events through delegation
- Lua基础语法学习
- [ACTF新生赛2020]crypto-aes
- 4小时定单破20000+,自称“百万内最豪华”,国产品牌飘了?
- 五子棋人机对战实现
- Redis distributed lock
- NDK series (6): let's talk about the way and time to register JNI functions
- Redis 哈希Hash底层数据结构
- 为什么 Redis 集群要使用反向代理? 看这篇就明白了
- CaEGCN: Cross-Attention Fusion based Enhanced Graph Convolutional Network for Clustering 2021
猜你喜欢
随机推荐
【JS 逆向百例】某公共资源交易网,公告 URL 参数逆向分析
Sort sort
真的很难理解?RecyclerView 缓存机制到底是几级缓存?
Using the optical fingerprint scheme under the huiding screen, Samsung Galaxy a71 5g is listed
[NCTF2019]babyRSA1
面试官问线程安全的List,看完再也不怕了!
In 2019, the world's top ten semiconductor manufacturers: Intel returned to the first place, and apple rose sharply against the trend
软件运维监控有哪些?
UE4 official AEC blueprint case course learning notes
Redis distributed lock
Calling dht11/22 temperature and humidity sensor in Proteus simulation Arduino
Error:svn: E155010: ‘/Users/.../Desktop/wrokspace/xxx‘ is scheduled for addition, but is missing
基于mediapipe的姿态识别和简单行为识别
解密 OOM 崩溃下降 90% 的秘密~
How to use C WinForm to copy files and display progress
Those "experiences and traps" in the data center
4小时定单破20000+,自称“百万内最豪华”,国产品牌飘了?
NDK series (6): let's talk about the way and time to register JNI functions
This is the most concise guide to tcpdump in history. It's enough to read this one
BUU-CTF basic rsa

![[C language] address book (dynamic version)](/img/29/3df19c187bee31ee4671e12d7cc7ff.jpg)


![[GWCTF 2019]BabyRSA1](/img/31/6727fd04be13ddd6bd46969fe2c50f.png)




