BatchForkTask
package com.shby.core.common;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
* @author: 李小龙
* @description:JAVA开发
* @created:2019/9/6
* @modified by 李小龙 on 2019/9/6
*/
public class BatchForkTask<T> extends RecursiveTask<T> {
List objectList;
ForkProcess process;
private static final int THRESHOLD = 3;
public BatchForkTask(List objectList, ForkProcess process) {
this.objectList = objectList;
this.process = process;
}
@Override
protected T compute() {
if (objectList.size() < THRESHOLD) {
return process.process(objectList);
} else {
//如果要插入的数据大于等于3,则进行分组插入
int size = objectList.size();
//第一个分组
BatchForkTask<T> aTask = new BatchForkTask(objectList.subList(0, size / 2), process);
//第二个分组
BatchForkTask<T> bTask = new BatchForkTask(objectList.subList(size / 2, objectList.size()), process);
//两个任务并发执行起来
invokeAll(aTask, bTask);
//两个分组的插入的行数加起来
return process.combine(aTask.join(), bTask.join());
}
}
public static<D> D invokeFork(List objects, ForkProcess processer, int threadCount) {
ForkJoinPool forkJoinPool = new ForkJoinPool(threadCount);
BatchForkTask<D> batchForkTask = new BatchForkTask(objects, processer);
ForkJoinTask<D> reslut = forkJoinPool.submit(batchForkTask);
D serials = null;
try {
serials = reslut.get();
} catch(Exception e) {
e.printStackTrace();
}
return serials;
}
}
ForkProcess
package com.shby.core.common;
import java.util.ArrayList;
import java.util.List;
/**
* @author: 李小龙
* @description:JAVA开发
* @created:2019/9/6
* @modified by 李小龙 on 2019/9/6
*/
public interface ForkProcess {
<T> T process(List objectList);
/**
* 默认实现
* @param obj
* @param obj2
* @param <T>
* @return
*/
default <T> T combine(T obj, T obj2) {
if(obj instanceof List) {
List list = new ArrayList();
list.addAll((List)obj);
list.addAll((List)obj2);
return (T) list;
} else {
StringBuffer buffer = new StringBuffer();
buffer.append(obj);
buffer.append(obj2);
return (T) buffer.toString();
}
}
}
Test测试
@Test
public void forkJoin() {
// ForkJoinPool commonPool = ForkJoinPool.commonPool();
List<ImsStockInOrderSerialDTO> imsStockInOrderSerialDTOList = new ArrayList<ImsStockInOrderSerialDTO>();
for(int i=0; i<100000; i++) {
ImsStockInOrderSerialDTO imsStockInOrderSerialDTO = new ImsStockInOrderSerialDTO();
imsStockInOrderSerialDTO.setSerialNo("ER1234499292929" + i);
imsStockInOrderSerialDTO.setSerialStatus(StatusFlag.SF_DEFAULT.CODE);
imsStockInOrderSerialDTOList.add(imsStockInOrderSerialDTO);
}
String serials = BatchForkTask.invokeFork(imsStockInOrderSerialDTOList, new ForkProcess(){
@Override
public String process(List objectList) {
StringBuffer buffer = new StringBuffer();
for(Object dto : objectList) {
ImsStockInOrderSerialDTO sdto = (ImsStockInOrderSerialDTO) dto;
buffer.append(sdto.getSerialNo());
}
return buffer.toString();
}
}, 10);
System.out.println(serials);
}