目录
public interface BatchFunction<I, O> {
O execute(I i);
String getFunctionName();
}
public abstract class AbstractBatchFunction<I, O> implements BatchFunction<I, O>{
@Override
public String getFunctionName(){
return this.getClass().getName();
}
}
public class BatchUtil {
public static <I, O> List<O> batch(List<I> inputList, final BatchFunction<I, O> batchFunction){
return batch(inputList, batchFunction, BatchExecutorService.THREAD_POOL_EXECUTOR);
}
public static <I, O> List<O> batch(List<I> inputList, final BatchFunction<I, O> batchFunction, ExecutorService executorService){
long startTime = System.currentTimeMillis();
String functionName = batchFunction.getFunctionName();
List<O> batchOutput = new ArrayList<>();
List<Callable<O>> batchCallableList = new ArrayList<>();
for(final I input : inputList){
batchCallableList.add(new Callable<O>() {
@Override
public O call() throws Exception {
return batchFunction.execute(input);
}
});
}
try{
List<Future<O>> futureList = executorService.invokeAll(batchCallableList, 2000, TimeUnit.MILLISECONDS);
for(Future<O> future : futureList){
try{
O o = future.get();
if(o == null){
continue;
}
batchOutput.add(o);
}catch (Exception e){
//日志
}
}
}catch (Exception e){
//日志
}
return batchOutput;
}
}