Java批量更新插入太慢?list分段+多线程处理
前言
当需要插入或修改大量数据时,我们会选择mybatis的批处理,但是这存在一些弊端
- 数据量极大时会很慢,小号数据库性能
- 大数据量的时候超过单次批量插入限制,数据会插入不进去
针对以上问题,拆分list和多线程处理,会很好解决。
整体流程
具体步骤
- 获取大list
- 拆分成list
- 线程池操作小list
具体代码实现
拆分集合的工具类
方式1:效果较差
public static <T> List<List<T>> spitList0(List<T> source, int length) {
long start = System.currentTimeMillis();
List<List<T>> result = new ArrayList<>();
if (CollectionUtils.isEmpty(source) || length <= 0) {
return result;
}
int size = source.size();
if (size <= length) {
result.add(source);
return result;
}
List<T> temp = new ArrayList<>();
for (int i = 0; i < size; i++) {
T index = source.get(i);
temp.add(index);
int tsize = temp.size();
if (tsize % length == 0 && tsize != 0) {
result.add(temp);
temp = new ArrayList<>();
}
}
if (!CollectionUtils.isEmpty(temp)) {
result.add(temp);
}
System.out.println(System.currentTimeMillis() - start);
return result;
}
方式2:效果较好
public static <T> List<List<T>> spitList(List<T> source, int length) {
long start = System.currentTimeMillis();
List<List<T>> result = new ArrayList<>();
if (CollectionUtils.isEmpty(source) || length <= 0) {
return result;
}
int size = source.size();
if (size <= length) {
result.add(source);
return result;
}
while (size > length) {
List<T> ts = source.subList(0, length);
result.add(ts);
List<T> ts1 = source.subList(length, size);
source = ts1;
size = source.size();
}
result.add(source);
System.out.println(System.currentTimeMillis() - start);
return result;
}
效果对比
多线程处理list
@Test
public void threadMethod() {
List<User> totalList = new ArrayList();
for (int i = 0; i < 1000; i++) {
User us = new User();
us.setAge(i);
us.setName("zhyang" + i);
totalList.add(us);
}
// 初始化线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 40,
5, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
// 大集合拆分成N个小集合
List<List<User>> lists = spitList(totalList, 100);
// 记录单个任务的执行次数
CountDownLatch countDownLatch = new CountDownLatch(lists.size());
// 对拆分的集合进行批量处理, 先拆分的集合, 再多线程执行
for (List<User> singleList : lists) {
// 线程池执行
threadPool.execute(new Thread(new Runnable() {
@Override
public void run() {
// 插入数据库的逻辑
}
}));
// 任务个数 - 1, 直至为0时唤醒await()
countDownLatch.countDown();
}
try {
// 让当前线程处于阻塞状态,直到锁存器计数为零
countDownLatch.await();
} catch (InterruptedException e) {
System.out.println("fail");
}
// 继续执行
}
@Data
class User {
private String name;
private int age;
}