前言
ArrayList 不是线程安全的
ArrayList 的 add 操作源码
/**
* 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) {
// 判断列表的capacity容量是否足够,是否需要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 将元素添加进列表的元素数组里面
elementData[size++] = e;
return true;
}
多线程处理 list
多线程分治处理 10G 数据
示例
同时修改最多约5万条数据
,而且还不支持批量或异步修改操作
。于是只能写个 for 循环操作,但操作耗时太长
循环操作的代码
循环修改整体耗时约 1分54秒,且代码中没有手动事务控制应该是自动事务提交
,所以 每次操作 事务都会提交
所以操作比较慢,我们对代码中添加手动事务控制
/***
* 一条一条依次对50000条数据进行更新操作
* 耗时:2m27s,1m54s
*/
@Test
void updateStudent() {
List<Student> allStudents = studentMapper.getAll();
allStudents.forEach(s -> {
//更新教师信息
String teacher = s.getTeacher();
String newTeacher = "TNO_" + new Random().nextInt(100);
s.setTeacher(newTeacher);
studentMapper.update(s);
});
}
使用手动事务的操作代码
添加手动事务操控制后,整体耗时约 24秒,这相对于自动事务提交的代码
,快了约5倍,对于大量循环数据库提交操作,添加手动事务可以有效提高操作效率
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;
/**
* 由于希望更新操作 一次性完成,需要手动控制添加事务
* 耗时:24s
* 从测试结果可以看出,添加事务后插入数据的效率有明显的提升
*/
@Test
void updateStudentWithTrans() {
List<Student> allStudents = studentMapper.getAll();
TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
//这里 不是每条 update 都提交事务了,相当于所有数据 update 完,再 commit
try {
allStudents.forEach(s -> {
//更新教师信息
String teacher = s.getTeacher();
String newTeacher = "TNO_" + new Random().nextInt(100);
s.setTeacher(newTeacher);
studentMapper.update(s);
});
dataSourceTransactionManager.commit(transactionStatus);
} catch (Throwable e) {
dataSourceTransactionManager.rollback(transactionStatus);
throw e;
}
}
多线程进行数据修改
StudentServiceImpl.java
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;
@Override
public void updateStudents(List<Student> students, CountDownLatch threadLatch) {
TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
System.out.println("子线程:" + Thread.currentThread().getName());
try {
students.forEach(s -> {
// 更新教师信息
// String teacher = s.getTeacher();
String newTeacher = "TNO_" + new Random().nextInt(100);
s.setTeacher(newTeacher);
studentMapper.update(s);
});
dataSourceTransactionManager.commit(transactionStatus);
threadLatch.countDown();
} catch (Throwable e) {
e.printStackTrace();
dataSourceTransactionManager.rollback(transactionStatus);
}
}
}
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;
@Autowired
private StudentService studentService;
/**
* 对用户而言,27s 任是一个较长的时间,我们尝试用多线程的方式来经行修改操作看能否加快处理速度
* 预计创建10个线程,每个线程进行5000条数据修改操作
* 耗时统计
* 1 线程数:1 耗时:25s
* 2 线程数:2 耗时:14s
* 3 线程数:5 耗时:15s
* 4 线程数:10 耗时:15s
* 5 线程数:100 耗时:15s
* 6 线程数:200 耗时:15s
* 7 线程数:500 耗时:17s
* 8 线程数:1000 耗时:19s
* 8 线程数:2000 耗时:23s
* 8 线程数:5000 耗时:29s
*/
@Test
void updateStudentWithThreads() {
//查询总数据
List<Student> allStudents = studentMapper.getAll();
// 线程数量
final Integer threadCount = 100;
//每个线程处理的数据量
final Integer dataPartionLength = (allStudents.size() + threadCount - 1) / threadCount;
// 创建多线程处理任务
ExecutorService studentThreadPool = Executors.newFixedThreadPool(threadCount);
CountDownLatch threadLatchs = new CountDownLatch(threadCount);
// 这里可以用 ListUtils.partition 将 list 分割
for (int i = 0; i < threadCount; i++) {
// 每个线程处理的数据
List<Student> threadDatas = allStudents.stream()
.skip(i * dataPartionLength).limit(dataPartionLength).collect(Collectors.toList());
studentThreadPool.execute(() -> {
studentService.updateStudents(threadDatas, threadLatchs);
});
}
try {
// 倒计时锁设置超时时间 30s
threadLatchs.await(30, TimeUnit.SECONDS);
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("主线程完成");
}
根据表格,我们线程数增大提交速度并非一直增大
,在当前情况下约在2-5个线程数时,提交速度最快(实际线程数还是需要根据服务器配置实际测试
)。
总结
对于大批量数据库操作,使用手动事务提交可以很多程度上提高操作效率
多线程对数据库进行操作时,并非线程数越多操作时间越快,按上述示例大约在2-5个线程时操作时间最快
对于多线程阻塞事务提交时,线程数量不能过多
如果能有办法实现批量更新那是最好
可能出现的问题
数组越界异常 ArrayIndexOutOfBoundsException
由于 ArrayList 添加元素是如上面分两步进行
,可以看出第一个不安全的隐患,在多个线程进行add操作
时可能会导致elementData数组越界
。
具体逻辑如下:
列表大小为9,即size=9
线程A 开始进入add方法,这时它获取到 size 的值为9,调用 ensureCapacityInternal 方法进行容量判断。
线程B 此时也进入add方法,它获取到 size 的值也为9,也开始调用 ensureCapacityInternal 方法。
线程A 发现需求大小为10,而 elementData 的大小就为10,可以容纳。于是它不再扩容,返回。
线程B 也发现需求大小为10,也可以容纳,返回。
线程A 开始进行设置值操作, elementData[size++] = e 操作。此时size变为10。
线程B 也开始进行设置值操作,它尝试设置 elementData[10] = e
而 elementData 没有进行过扩容,它的下标最大为9
于是此时会报出一个数组越界的异常ArrayIndexOutOfBoundsException.
元素值覆盖和为空问题
elementData[size++] = e
设置值的操作同样会导致线程不安全。从这儿可以看出,这步操作也不是一个原子操作
,它由如下两步操作构成:
elementData[size] = e;
size = size + 1;
在单线程执行这两条代码时没有任何问题,但是当多线程环境下执行
时,可能就会发生一个线程的值覆盖另一个线程添加的值
,具体逻辑如下:
列表大小为0,即size=0
线程A 开始添加一个元素,值为A。此时它执行第一条操作,将 A 放在了 elementData 下标为0 的位置上。
接着 线程B 刚好也要 开始添加一个值为 B 的元素,且走到了第一步操作。此时 线程B 获取到 size 的值 依然为0,于是它将B也 放在了elementData下标为0 的位置上。
线程A 开始将size的值增加为 1
线程B 开始将size的值增加为 2
这样线程AB执行完毕后,理想中情况为size为2,elementData下标0 的位置为A,下标1 的位置为B。
而实际情况变成了 size 为2,elementData下标为0 的位置变成了 B,下标1 的位置上什么都没有。
并且后续除非使用set方法修改此位置的值,否则将一直为null
因为size为2,添加元素时会从下标为2的位置上开始。
代码示例
@SneakyThrows
public static void threadTest() {
final List<Integer> list = new ArrayList<>();
new Thread(() -> {
for (int i = 1; i < 1000; i++) {
list.add(i);
System.out.println("添加第 " + i + "个元素 :" + i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 1001; i < 2000; i++) {
list.add(i);
System.out.println("添加第 " + i + "个元素 :" + i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(3000);
System.out.println("list size:" + list.size());
}
执行过程中,两种情况出现如下:
1、元素值覆盖和为空问题
2、报数组越界异常 ArrayIndexOutOfBoundsException 错误
代码示例2
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 10000000; i >= 1; i--) {
list.add(0);
}
System.out.println("源集合数量:"+list.size());
List<Integer> newList = new ArrayList<>();
long start = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(100);
for (Integer integer : list) {
executor.submit(()->{
newList.add(integer+1);
});
}
executor.shutdown();
try {
executor.awaitTermination(6, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("时间:"+(end-start)+"ms");
System.out.println("新集合数量:"+newList.size());
}
public static void main(String[] args) {
ArrayList<Integer> list = Lists.newArrayList();
for (int i = 10000000; i >= 1; i--) {
list.add(0);
}
System.out.println("源集合数量:" + list.size());
Stopwatch started = Stopwatch.createStarted();
List<Integer> newList = new ArrayList<>();
ForkJoinPool forkJoinPool = new ForkJoinPool(100, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
list.forEach(item ->
CompletableFuture.runAsync(() -> {
newList.add(item + 1);
}, forkJoinPool)
);
System.out.println("时间:" + started.elapsed(TimeUnit.SECONDS));
System.out.println("新集合数量:" + newList.size());
}
使用线程池给 ArrayList 添加一千万个元素
。来看下结果:
数据会少于一千万
因为 ArrayList 不是线程安全的,在高并发情况下对list进行数据添加会出现数据丢失的情况。
并且 一个线程在遍历List , 另一个线程 修改List ,会报 ConcurrentModificationException (并发修改异常)错误
ArrayList线程安全处理
Collections.synchronizedList
最常用的方法是通过 Collections 的 synchronizedList
方法将 ArrayList 转换成线程安全的容器
后再使用
List<Object> list = Collections.synchronizedList(new ArrayList<>());
list.add()方法加锁
代码示例2
使用 synchronizedList
,时间上和 Vector差距不大
,因给给ArrayList进行了包装以后等于是给ArrayList
里面所有的方法都加上了 synchronized
,和Vector实现效果差不多
list 方法加锁
synchronized(list.get()) {
list.get().add(model);
}
Vector
使用 Vector
类进行替换,将上文的public static List arrayList = new ArrayList();
替换为public static List arrayList = new Vector<>();
原理: 使用了synchronized
关键字进行了加锁处理
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
代码示例2
使用 Vector ,时间上要长于ArrayList
CopyOnWriteArrayList
使用线程安全的 CopyOnWriteArrayList
代替线程不安全的 ArrayList
List<Object> list = new CopyOnWriteArrayList<Object>();
原理: 使用mutex
对象进行维护
处理,Object mutex = new Object()
就是创建了一个临时空间
用于辅助独占的处理
ThreadLocal
使用 ThreadLocal
使用ThreadLocal变量确保线程封闭性
(封闭线程往往是比较安全的, 但由于使用ThreadLocal封装变量,相当于把变量丢进执行线程中去,每new一个新的线程,变量也会new一次,一定程度上会造成性能[内存]损耗
,但其执行完毕就销毁的机制使得ThreadLocal变成比较优化的并发解决方案
)。
ThreadLocal<List<Object>> threadList = new ThreadLocal<List<Object>>() {
@Override
protected List<Object> initialValue() {
return new ArrayList<Object>();
}
};
其他
涉及到并发问题 参考 CountDownLatch