集合源码分析-线程安全的list
Vector 与 ArryaList 的差异
增加了一个可以控制扩容增量的构造方法
1
2
3
4
5
6
7
8public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
修改了默认扩容机制
1
2
3
4
5
6
7
8
9
10
11
12private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//在没有初始化扩容增量的时候,默认扩容为原来的2倍
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}在修改元素的方法上面增加了同步锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
public boolean remove(Object o) {
return removeElement(o);
}因为在操作元素的方法上面增加了同步锁,所以查询效率上面 ArryaList 更快
CopyOnWriteArrayList
public void add(int index, E element)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27public void add(int index, E element) {
final ReentrantLock lock = this.lock;
//通过lock保证单线程执行
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (index > len || index < 0)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+len);
Object[] newElements;
int numMoved = len - index;
if (numMoved == 0)
newElements = Arrays.copyOf(elements, len + 1);
else {
newElements = new Object[len + 1];
//index前后数组拷贝
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index, newElements, index + 1,
numMoved);
}
newElements[index] = element;
setArray(newElements);
} finally {
lock.unlock();
}
}通过上述代码可以发现 CopyOnWriterArrayList 实现实现安全的方法为在插入数据时,通过 lock 增加锁,每次在新增数据的时候,都重新新建一个数组,把原有的数组拷贝过来。这也能够保证用户的读取不会受到现在修改的数组影响。对数据读取更优秀,但是因为是拷贝数组,所以更新数据的时候代价更高,效率更低。
public E get(int index)
1
2
3
4
5
6
7
8
9
10
11private transient volatile Object[] array;
public E get(int index) {
return get(getArray(), index);
}
private E get(Object[] a, int index) {
return (E) a[index];
}在查询数据的时候,没有使用 synchronize 的同步代码块,而是通过
1 | private transient volatile Object[] array; |
在查询数据的时候,没有使用 synchronize 的同步代码块,而是通过 volatile 关键字保证可见性。这样可以提高查询的效率
CopyOnWriteArryalist 和 Vector 的区别
- Vector 对于读取操作都加上了 synchronize 同步锁,这样效率会更慢一些
- CopyOnWriteArryalist 通过对写数据加 lock 锁。读数据通过 volatile 保证可见,但是在插入数据的时候是复制原有数据,这样的话,查询更快,插入更慢一些
Collections.SynchronizedList
基本实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64SynchronizedList(List<E> list) {
super(list);
this.list = list;
}
SynchronizedList(List<E> list, Object mutex) {
super(list, mutex);
this.list = list;
}
public boolean equals(Object o) {
if (this == o)
return true;
synchronized (mutex) {return list.equals(o);}
}
public int hashCode() {
synchronized (mutex) {return list.hashCode();}
}
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);}
}
public int indexOf(Object o) {
synchronized (mutex) {return list.indexOf(o);}
}
public int lastIndexOf(Object o) {
synchronized (mutex) {return list.lastIndexOf(o);}
}
public boolean addAll(int index, Collection<? extends E> c) {
synchronized (mutex) {return list.addAll(index, c);}
}
public ListIterator<E> listIterator() {
return list.listIterator(); // Must be manually synched by user
}
public ListIterator<E> listIterator(int index) {
return list.listIterator(index); // Must be manually synched by user
}
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return new SynchronizedList<>(list.subList(fromIndex, toIndex),
mutex);
}
}
public void replaceAll(UnaryOperator<E> operator) {
synchronized (mutex) {list.replaceAll(operator);}
}
public void sort(Comparator<? super E> c) {
synchronized (mutex) {list.sort(c);}
}可以看到基本上还是通过 synchronize 同步代码块实现的
特点
- 同步代码块锁定的范围更少
- 可以将 list 下面的任意实现转化成线程安全的集合
- 但是在迭代 SynchronizedList 是需要手动进行同步处理
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 zeofuns!