亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

由于 RaceCondtion,使用流迭代 LinkedList 正在改變結果列表

由于 RaceCondtion,使用流迭代 LinkedList 正在改變結果列表

慕少森 2022-06-04 15:44:45
我們正在使用 java8 中的 Streams 迭代 LinkedList,并創建另一個列表。但是由于競爭條件,結果列表大小發生了變化。List<DesInfo> InfoList = new LinkedList<>();documentList.stream()             .parallel()             .forEach(document -> {                 Info descriptiveInfo = objectFactory.createDescriptiveInfo();                 List<Document> documents = new ArrayList<>();                 documents.add(document);                 descriptiveInfo.setHotelInfo(getHotelInfo(document.get(CODE), documents));                 InfoList.add(Info);             });如果我們每次看到為相同的 documentList 輸入生成不同大小的 InfoList 時都會運行此代碼。我瀏覽了一些論壇,他們提到 LinkedList 不是線程安全的,而是使用任何線程安全的集合。但我的要求不允許我改變 LinkedList。我需要使用具有相同 LinkedList 的并行流功能。
查看完整描述

2 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

而不是使用forEachuse aCollector和 amap()操作:

List<HotelDescriptiveInfo> hotelDescriptiveInfoList = documentList.parallelStream()
    .map(document -> {
        HotelDescriptiveInfo descriptiveInfo = objectFactory.createHotelDescriptiveInfo();
        List<Document> documents = new ArrayList<>();
        documents.add(document);
        descriptiveInfo.setHotelInfo(getHotelInfo(document.get(HOTEL_CODE), documents));
        return descriptiveInfo;
    })
    .collect(Collectors.toCollection(LinkedList::new));

Streamapi 將負責處理并且不允許競爭條件。


查看完整回答
反對 回復 2022-06-04
?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

使用collect而不是更改集合的狀態。

首先創建一個映射函數:

private DesInfo documentToDesInfo(Document document){
    DesInfo info = objectFactory.createDescriptiveInfo();
    List<Document> documents = new ArrayList<>();
    documents.add(document);
    info.setHotelInfo(getHotelInfo(document.get(CODE), documents));
    return info;}

然后在您的管道中使用它:

List<DesInfo> infoList = documentList.parallelStream()
                                     .map(this::documentToDesInfo)
                                     .collect(toCollection(LinkedList::new));


查看完整回答
反對 回復 2022-06-04
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號