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

边栏推荐
- [MRCTF2020]babyRSA
- 资深如何确定软件测试结束的标准
- Redis的分布式锁
- 2022/7/26
- BUUCTF-[BJDCTF2020]RSA1
- Solve 5g pain points, Meizu 17 smart 5g fast and stable technology release
- What technology is RPA process automation robot? How to realize office automation?
- BUUCTF-Dangerous RSA
- 测试类中的断言机制
- What is the difference between concurrency and parallelism?
猜你喜欢

Lua basic grammar learning

Realization of gobang man-machine combat

Ideas, methods and steps of making folding fans with 3DMAX

(十二)51单片机----用DS18B20浅测一下工(江)西的室外温度

BUUCTF-RSA

29.学习Highcharts 使用百分比的堆叠柱形图

Put cloudflare on the website (take Tencent cloud as an example)

2022年土木,建筑与环境工程国际会议(ICCAEE 2022)

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

Decrypt the secret of 90% reduction in oom crash~
随机推荐
[RoarCTF2019]RSA
为什么需要等待计时2MSL?
[GWCTF 2019]BabyRSA1
Error:svn: E155010: ‘/Users/.../Desktop/wrokspace/xxx‘ is scheduled for addition, but is missing
JUC toolkit learning
2022 International Conference on civil, building and Environmental Engineering (iccaee 2022)
Redis 哈希Hash底层数据结构
29. Learn the stacked column chart of highcharts using percentage
XSS Payload 学习浏览器解码
Explain the idempotence of distributed system in detail
真的很难理解?RecyclerView 缓存机制到底是几级缓存?
Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further
js数组复制速度测试220320
Character stream learning 14.3
MySQL data query (where)
Reduce error demonstration
BUUCTF-Dangerous RSA
BUUCTF-RSA4
Smartrefresh nested multiple recycleview sliding conflicts and incomplete layout display
76000 people shut down! Toshiba announced the closure of all factories in Japan