因为parallelStream使用了多线程所以难以保证线程安全,容易导致数据的丢失
原本代码:不安全
public List<List<Object>> getReportListBody(List<ReportList> ReportLists) {
List<List<Object>> result = new LinkedList<>();
ReportLists.parallelStream().forEach(reportList -> {
List<Object> row = new LinkedList<>();
...处理代码
result.add(row);
});
现代码:
public List<List<Object>> getReportListBody(List<ReportList> ReportLists) {
List<List<Object>> result = Collections.synchronizedList(new LinkedList<>());
ReportLists.parallelStream().forEach(reportList -> {
List<Object> row = new LinkedList<>();
...处理代码
result.add(row);
});
synchronizedList的源码:
final Object mutex; // Object on which to synchronize
public void add(int index, E element) {
synchronized (mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized (mutex) {return list.remove(index);}
}
synchronizedList的add和remove都是被synchronized修饰的所以可以保证线程安全,不会导致数据丢失
推荐的方式:
List<List<Object>> result = ReportLists.parallelStream().map(reportList -> {
List<Object> row = new LinkedList<>();
...处理代码
return row;
}).collect(Collectors.toList());
错误的版本:
public List<List<Object>> getReportListBody(List<ReportList> ReportLists) {
List<List<Object>> result = new LinkedList<>();
synchronized (result){
ReportLists.parallelStream().forEach(reportList -> {
List<Object> row = new LinkedList<>();
...处理代码
result.add(row);
});
}
我本以为给result加锁就能够保证线程安全,但是结果还是丢了数据
目前还不清楚为什么