隊列+線程池消費致使ConcurrentModificationException

@Autowired
    PieceSearchDao pieceSearchDao;
    public void getInfoFromIntopieces() {
        try{

            List<IntopieceByEagleDTO> list = pieceSearchDao.queryForInsert();
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            List<? extends Callable<String>> lists = Lists.newArrayList();
            List<IntopieceByEagleDTO> dtoList = Lists.newArrayList();
            int index = 1;
            for (IntopieceByEagleDTO intopieceByEagleDTO : list){
                dtoList.add(intopieceByEagleDTO);
                if(index  % 2000 == 0){
                    writeFileLoadFile writeFileLoadFile = new writeFileLoadFile();
                    writeFileLoadFile.setFileName(index);
                    writeFileLoadFile.setIntopieceByEagleDTOS(dtoList);
                    executorService.submit(writeFileLoadFile);
                    dtoList = Lists.newArrayList();
//                    dtoList.clear();
                }
                index++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Data
    class writeFileLoadFile implements Callable<String>{

        private List<IntopieceByEagleDTO> intopieceByEagleDTOS;
        private int fileName;

        @Override
        public String call(){
            try{
                StringBuffer fraudapi = new StringBuffer();
                for(IntopieceByEagleDTO intopieceByEagleDTO : intopieceByEagleDTOS){
                    fraudapi.append(fileName + "\""+intopieceByEagleDTO.getPieces_no_id()+"\",\"413026199008196372\",\"13837132012\",\"1423577433586-67438719\",1,\"Accept\",\"\\N\",\"result\",\"1423577432\",\\N,");
                    fraudapi.append("\r\n");
                }
                FileKit.appendString(fraudapi.toString(),"D:\\aa","utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            return "";
        }
    }
複製代碼

報錯信息: java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.migration.eagle.manager.InsertDataManager$writeFileLoadFile.call(InsertDataManager.java:59)java

【問題】:在隊列中,產生生產者list,傳入消費者線程中,並清空list,同時再進行下一個list的生產,致使在線程中的list獲取時,是一點點增長到預約值/直接報錯;api

【緣由】:在用完list後,使用了list.clear();致使此list可能還未被消費,便進行了clear,或者在消費中; 會形成list的併發問題;list的引用傳入了線程中,如需從新定義list/list消費後清空,應該是從新定義list;bash

【解決】:正確處理方法: list.clear(); 改成:——————list = Lists.newArrayList();併發

相關文章
相關標籤/搜索