集合操作 Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class NotSafeDemo {

/**
* 多个线程同时对集合进行修改
* @param args
*/
public static void main(String[] args) {
List list = new ArrayList();

for (int i = 0; i < 10; i++) {
new Thread(() ->{
list.add(UUID.randomUUID().toString());
System.out.println(list);
}, "线程" + i).start();
}
}
}

异常内容

java.util.ConcurrentModificationException

问题: 为什么会出现并发修改异常?

查看 ArrayList 的 add 方法源码,线程不安全

1
2
3
4
5
6
7
8
9
10
11
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

那么我们如何去解决 List 类型的线程安全问题?

Vector

Vector 是矢量队列,它是 JDK1.0 版本添加的类。继承于 AbstractList,实现了 List, RandomAccess, Cloneable 这些接口。

Vector 继承了 AbstractList,实现了 List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能

Vector 实现了 RandmoAccess 接口,即提供了随机访问功能。RandmoAccess 是 java 中用来被 List 实现,为 List 提供快速访问功能的

Vector 中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。

Vector 实现了 Cloneable 接口,即实现 clone()函数。它能被克隆。

和 ArrayList 不同,Vector 中的操作是线程安全的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class NotSafeDemo {

/**
* 多个线程同时对集合进行修改
* @param args
*/
public static void main(String[] args) {
List list = new Vector();

for (int i = 0; i < 10; i++) {
new Thread(() ->{
list.add(UUID.randomUUID().toString());
System.out.println(list);
}, "线程" + i).start();
}
}
}

现在没有运行出现并发异常,为什么?

查看 Vector 的 add 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Appends the specified element to the end of this Vector.
*
* @param e element to be appended to this Vector
* @return {@code true} (as specified by {@link Collection#add})
* @since 1.2
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}

add 方法被 synchronized 同步修辞,线程安全,因此没有并发异常,但是 synchronized 的效率低,很少使用

Collections

Collections 提供了方法 synchronizedList 保证 list 是同步线程安全的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class NotSafeDemo {

/**
* 多个线程同时对集合进行修改
* @param args
*/
public static void main(String[] args) {
List list = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < 100; i++) {
new Thread(() ->{
list.add(UUID.randomUUID().toString());
System.out.println(list);
}, "线程" + i).start();
}
}
}

没有并发修改异常

查看方法源码

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
/**
* Returns a synchronized (thread-safe) list backed by the specified
* list. In order to guarantee serial access, it is critical that
* <strong>all</strong> access to the backing list is accomplished
* through the returned list.<p>
*
* It is imperative that the user manually synchronize on the returned
* list when iterating over it:
* <pre>
* List list = Collections.synchronizedList(new ArrayList());
* ...
* synchronized (list) {
* Iterator i = list.iterator(); // Must be in synchronized block
* while (i.hasNext())
* foo(i.next());
* }
* </pre>
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned list will be serializable if the specified list is
* serializable.
*
* @param <T> the class of the objects in the list
* @param list the list to be "wrapped" in a synchronized list.
* @return a synchronized view of the specified list.
*/
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<>(list) :
new SynchronizedList<>(list));
}

Collections 构建的线程安全集合

CopyOnWriteArrayList

首先我们对 CopyOnWriteArrayList 进行学习,其特点如下:

它相当于线程安全的 ArrayList。和 ArrayList 一样,它是个可变数组;但是和 ArrayList 不同的时,它具有以下特性:

  1. 它最适合于具有以下特征的应用程序:List 大小通常保持很小,只读操作远多于可变操作,需要在遍历期间防止线程间的冲突。
  2. 它是线程安全的。
  3. 因为通常需要复制整个基础数组,所以可变操作(add()、set() 和 remove() 等等)的开销很大。
  4. 迭代器支持 hasNext(), next()等不可变操作,但不支持可变 remove()等操作。
  5. 使用迭代器进行遍历的速度很快,并且不会与其他线程发生冲突。在构造迭代器时,迭代器依赖于不变的数组快照。

1. 独占锁效率低:采用读写分离思想解决

2. 写线程获取到锁,其他写线程阻塞

3. 复制思想:

当我们往一个容器添加元素的时候,不直接往当前容器添加,而是先将当前容器进行 Copy,复制出一个新的容器,然后新的容器里添加元素,添加完元素之后,再将原容器的引用指向新的容器。

这时候会抛出来一个新的问题,也就是数据不一致的问题。如果写线程还没来得及写会内存,其他的线程就会读到了脏数据。

这就是 CopyOnWriteArrayList 的思想和原理。就是拷贝一份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class NotSafeDemo {

/**
* 多个线程同时对集合进行修改
* @param args
*/
public static void main(String[] args) {
List list = new CopyOnWriteArrayList();
for (int i = 0; i < 100; i++) {
new Thread(() ->{
list.add(UUID.randomUUID().toString());
System.out.println(list);
}, "线程" + i).start();
}
}
}

原因分析(重点):动态数组与线程安全

下面从“动态数组”和“线程安全”两个方面进一步对 CopyOnWriteArrayList 的原理进行说明。

  • “动态数组”机制

    • 它内部有个“volatile 数组”(array)来保持数据。在“添加/修改/删除”数据时,都会新建一个数组,并将更新后的数据拷贝到新建的数组中,最后再将该数组赋值给“volatile 数组”, 这就是它叫做 CopyOnWriteArrayList 的原因
    • 由于它在“添加/修改/删除”数据时,都会新建数组,所以涉及到修改数据的操作,CopyOnWriteArrayList 效率很低;但是单单只是进行遍历查找的话,效率比较高。
  • “线程安全”机制

    • 通过 volatile 和互斥锁来实现的。
    • 通过“volatile 数组”来保存数据的。一个线程读取 volatile 数组时,总能看到其它线程对该 volatile 变量最后的写入;就这样,通过 volatile 提供了“读取到的数据总是最新的”这个机制的保证。
    • 通过互斥锁来保护数据。在“添加/修改/删除”数据时,会先“获取互斥锁”,再修改完毕之后,先将数据更新到“volatile 数组”中,然后再“释放互斥锁”,就达到了保护数据的目的。

总结

List

ArrayList不是线程安全类,在多线程同时写的情况下,会抛出java.util.ConcurrentModificationException异常。

解决方法

  1. 使用VectorArrayList所有方法加synchronized,太重)
  2. 使用Collections.synchronizedList()转换成线程安全类
  3. 使用java.concurrent.CopyOnWriteArrayList(推荐)

Set

跟 List 类似,HashSetTreeSet都不是线程安全的,与之对应的有CopyOnWriteSet这个线程安全类。这个类底层维护了一个CopyOnWriteArrayList数组。

java.util.concurrent 并发包下CopyOnWriteArrayListCopyOnWriteArraySet 类型,通过动态数组与线程安全个方面保证线程安全

Map

HashMap 不是线程安全的,Hashtable 是线程安全的,但是跟 Vector 类似,底层通过 synchronized 关键字实现,效率太低。所以也有类似 CopyOnWriteMap,只不过叫 ConcurrentHashMap。

HashSet 和 HashMap

HashSet 线程不安全,为什么不安全?CopyOnWriteArraySet 为什么安全?

HashSet线程不安全,不安全的原因是因为HashMap不是线程安全的。HashSet底层是用HashMap实现的,既然是用HashMap实现的,那HashMap.put()需要传两个参数,而HashSet.add()只传一个参数,这是为什么?

实际上HashSet.add()就是调用的HashMap.put(),只不过 Value 被写死了,是一个 private static final Object 对象。

CopyOnWriteArraySet线程安全,底层使用的是CopyOnWriteArraySet