【问题标题】:How to use executor service in loop for each iteration?如何在每次迭代中循环使用执行器服务?
【发布时间】:2021-01-12 18:23:58
【问题描述】:
private ExecutorService executorService = Executors.newFixedThreadPool(3);

public void myMethod(){
    int batchSize = 2;
    // calling for 3 pages to test
    for(int i=0;i<3; i++) {
        int[] pageNum = {-1};
        executorService.execute(() -> {
            pageNum[0] = pageNum[0] + 1;
            fetchDataAndPushEvents(pageNum[0], batchSize);  
        }); 
    }
}
private void fetchDataAndPushEvents(int pageNum, int batchSize) {
    log.info("Fetching data for page number: {} and batch size: {}", pageNum, batchSize);
        
    long startTime = System.currentTimeMillis();
    Pageable pageable = PageRequest.of(pageNum, batchSize);
    List<AnswerDto> result = myService.getAllResponse(pageable).getContent();
    long secondTime = System.currentTimeMillis();
    log.info("Time taken to fetch data for page number: {} and batch size: {} is :{}", pageNum, batchSize, secondTime-startTime);

    if(!CollectionUtils.isEmpty(result)) {
        log.info("Pushing events for page number: {} and batch size: {}", pageNum, batchSize);
        pushSomeEvent(result);
        log.info("Time taken to push event for page number: {} and batch size: {} is :{}", pageNum, batchSize, System.currentTimeMillis()-secondTime);
        } else {
            // to terminate the process
            return;
        }
    }

我的目标是获取上面代码中提到的批量大小为 2(比如)和 3(比如)批量/页面的数据。我试图负责获取数据并将页面的事件推送到一个线程,即 1 个线程用于 1 个页面。我研究它并能够编写上述逻辑。

但是当我尝试运行上面的代码时,我从getAllResponse 存储库调用中获得了相同的 2 响应(作为批处理大小),用于所有三个迭代。 pageNum 没有更新。获取第 0 页的所有响应,因此在所有 3 次迭代中都会推送相同的事件。我应该如何解决这个问题? PS:我对executorService了解不多。

【问题讨论】:

    标签: java multithreading executorservice


    【解决方案1】:

    您没有增加 pageNum,它将在每次迭代中具有相同的值。 您必须使用单独的计数器变量,如下所示。

     int pageNum = 0; 
     for(int i=0, pageCounter=0;i<3; i++,pageCounter++) {
        executorService.execute(() -> {
            fetchDataAndPushEvents(pageNum + pageCounter, batchSize);  
        }); 
    }
    

    【讨论】:

    • 感谢您指出,我完全忘记了。另外,你能告诉我是否使用无限while循环while(true){}而不是上面有限的for循环,当result列表为空时,我应该如何退出/关闭执行程序服务?
    • 在while循环中添加条件,成功存在后调用执行器服务的shutdown/shutdownnow方法。
    猜你喜欢
    • 2021-06-07
    • 2014-10-21
    • 2016-10-31
    • 2013-04-24
    • 2018-01-11
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多