111

List不安全

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
package com.marlowe.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
* @program: juc
* @description: java.util.ConcurrentModificationException 并发修改异常
* @author: Marlowe
* @create: 2020-12-03 21:00
**/
public class ListTest {
public static void main(String[] args) {

/**
* 并发下ArrayList 不安全的
*
* 解决方法:
* 1、List<String> list = new Vector<>();
* 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
* 3、List<String> list = new CopyOnWriteArrayList<>();
*/

/**
* CopyOnWrite 写入时复制 COW 计算机程序设计领域的一种优化策略
* 多个线程调用的时候,list,读取的时候,固定的,写入的(覆盖)
* 在写入的时候避免覆盖,造成数据问题!
* CopyOnWriteArrayList 比 Vector 好在那里 前者是lock,后者是是synchronized
*/
List<String> list = new CopyOnWriteArrayList<>();

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

Set不安全

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
package com.marlowe.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
* @program: juc
* @description: 同理可证 :java.util.ConcurrentModificationException
* 1、Set<String> set = Collections.synchronizedSet(new HashSet<>());
* 2、Set<String> set = new CopyOnWriteArraySet<>();
* @author: Marlowe
* @create: 2020-12-03 21:53
**/
public class SetTest {
public static void main(String[] args) {
// Set<String> set = new HashSet<>();
// Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 30; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}

HashSet 底层是什么?

1
2
3
4
5
6
7
8
9
10
11
public HashSet() {
map = new HashMap<>();
}

// add set本质就是map key是无法重复的
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

// PRESENT
private static final Object PRESENT = new Object();

Map 不安全

回顾Map基本操作
20201203224234

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
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
* @program: juc
* @description: java.util.ConcurrentModificationException
* @author: Marlowe
* @create: 2020-12-03 22:11
**/
public class MapTest {
public static void main(String[] args) {

// map是这样用的吗?不是,工作中不用HashMap

// HashMap<String, String> map = new HashMap<>();

Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 30; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}

评论