你常用的集合类是啥?—ArrayList,HashSet,HashMap
1、单机版这肯定没啥问题,多线程环境下还好使吗?
2、有啥解决方案不?
3、为啥这种方案好使?
面对这一串三连问,有多少人能扛得住~且听我细细道来。。。
List<String> list= new ArrayList<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(Thread.currentThread().getName()+"————————"+list);
},String.valueOf(i)).start();
}
//30个线程同时插入数据到list
运行结果: -Exception in thread "4" java.util.ConcurrentModificationException
//不加锁-线程1正在对一个对象写,线程2抢夺此对象、导致数据不一致
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//追踪源码发现,不加任何锁~
有三种解决方案
1、List list= new Vector<>();
2、List list= Collections.synchronizedList(new ArrayList<>());
3、List list= new CopyOnWriteArrayList<>()
// new Vector<>(); 源码如下,发现有 synchronized
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
// protected Object[] elementData; 缺点:全局对象,synchronized 锁导致只能写或者读
return true;
}
//Collections.synchronizedList(new ArrayList<>()); 追踪发现也有 synchronized
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return new SynchronizedList<>(list.subList(fromIndex, toIndex),
mutex);
}
}
对于1,2解决方案不在多说,synchronized 起了关键作用,那么3又是如何的呢 ?
// 写时复制 读写分离--ReentrantLock
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
//线程1--copy原有数组,在最下边加一个
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
//替换原有数组
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
// setArray(newElements);
final void setArray(Object[] a) {
array = a;
}
对于这段代码通过图片理解,
通过图片结合代码发现,线程1 --add时、上锁,copy 原有数组、后边加一个,没有对原有对象 Object[] 整体加锁,保证了并发读不受影响、进一步保证了读写分离。
二、举一反三、new HashSet<>(); 存在同样的问题
Set set=new HashSet<>();
解决方案:
1、 set=Collections.synchronizedSet(new HashSet<>());
2、 set= new CopyOnWriteArraySet<>();
//HashSet
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
private static final Object PRESENT = new Object();
// CopyOnWriteArraySet
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
通过源码发现原理都一样,不过有个意外的发现。。HashSet 底层是hashmap,\add(E e) 添加的是key,value是一个常量–static final Object PRESENT = new Object();
三、举一反三、new HashMap<>(); 存在同样的问题
Map<String,Object> map=new HashMap<>();
解决方案:
1、map=Collections.synchronizedMap(new HashMap<String,Object>());
2、 map=new ConcurrentHashMap<>();
public boolean add(K e) {
V v;
if ((v = value) == null)
throw new UnsupportedOperationException();
return map.putVal(e, v, true) == null;
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}