问题:数据库迁移由于主从不一致产生的错误,在程序执行时并没有被发现,而是在观察数据时发现replace操作并没有真正的被执行。
原因:在进行replace操作时,使用了ExecutorService线程池,没有对线程的返回结果进行处理。而线程之间互不影响,主线程可以顺利执行。
一。具体示例
程序顺利执行
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class TestExecutorService {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(6);
int i = 10;
for (int index =1;index < 10; index ++) {
executorService.submit(() -> {
System.out.println("a");
throw new Exception();
}
);
}
executorService.shutdown();
}
}
对线程的异常进行获取处理
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class TestExecutorService2 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(6);
List<Future<String>> resultList = new ArrayList<Future<String>>();
int i = 10;
for (int index =1;index < 10; index ++) {
Future<String> result = executorService.submit(() -> {
System.out.println("a");
throw new Exception();
}
);
resultList.add(result);
}
for (Future<String> fs : resultList) {
try {
System.out.println(fs.get()); // 打印各个线程(任务)执行的结果
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
executorService.shutdownNow();
e.printStackTrace();
return;
}
}
executorService.shutdown();
}
}
二。记得关掉线程池
程序执行次数过多,创建过多的线程,可能会OOM。
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
三。一篇很好的博客:https://www.cnblogs.com/Steven0805/p/6393443.html