在CompletableFuture类和get方法中使用join方法

问题描述 投票:1回答:1

我想实现一个功能,其中大文件被分解成块并且处理可以并行发生。

我使用CompletableFuture并行运行任务。不幸的是,除非我使用加入,否则它不起作用。我很惊讶这种情况正在发生,因为根据文档,get也是类中的阻塞方法,它返回结果。有人可以帮我弄清楚我做错了什么。

//cf.join(); if i uncommnet this everything works

如果我在方法processChunk中取消注释上面的行,一切正常。我的价值观印刷了一切。但如果我删除它,没有任何反应。所有我得到的是期货已经完成的通知,但内容没有打印。

这是我的输出

i cmpleteddone
i cmpleteddone
i cmpleteddone
i cmpleteddone
i cmpleteddone

我的文本文件是一个非常小的文件(目前)

1212451,London,25000,Blocked 
1212452,London,215000,Open 
1212453,London,125000,CreditBlocked 
1212454,London,251000,DebitBlocked 
1212455,London,2500,Open 
1212456,London,4000,Closed 
1212457,London,25100,Dormant 
1212458,London,25010,Open 
1212459,London,27000,Open 
12124510,London,225000,Open 
12124511,London,325000,Open 
12124512,London,425000,Open 
12124513,London,265000,Open 
12124514,London,2577000,Open 
12124515,London,2504400,Open


package com.org.java_trial.thread.executors;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;




public class ProcessReallyBigFile {

    private static final ExecutorService ex = Executors.newFixedThreadPool(5);

    private static CompletableFuture<String> processChunk(List<String> lines) {

        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {

            //just for purposes of testing, will be replaced with major function later
            lines.stream().forEach(System.out::println);
            return "done";
        }, ex);

        //cf.join(); if i uncommnet this everything works
        return cf;
    }

    private static void readInChunks(String filepath, Integer chunksize) {

        List<CompletableFuture<String>> completable = new ArrayList<>();
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filepath))) {

            String line = null;
            List<String> collection = new ArrayList<String>();
            int count = 0;

            while ((line = reader.readLine()) != null) {

                if (count % chunksize == chunksize - 1) {

                    collection.add(line);
                    completable.add(processChunk(collection));

                    collection.clear();

                } else {

                    collection.add(line);
                }
                count++;
            }

            // any leftovers
            if (collection.size() > 0)
                completable.add(processChunk(collection));

        } catch (IOException e) {
            e.printStackTrace();
        }


        for (CompletableFuture c : completable) {
            c.join();
            if (c.isDone() || c.isCompletedExceptionally()) {
                try {

                    System.out.println("i cmpleted" + c.get());
                } catch (InterruptedException | ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        ex.shutdown();

    }

    public static void main(String[] args) {

        String filepath = "C:\\somak\\eclipse-workspace\\java_thingies\\java_trial\\account_1.csv";

        readInChunks(filepath, 3);
    }
}
java concurrency completable-future
1个回答
1
投票

原因是这样的:

collection.clear();

你的控件返回没有.join()的调用方法和你的任务所指的集合被清除。 luck you ain't getting an exception thrown for concurrent access。应始终同步对共享资源的并发访问。我宁愿这样做:

synchronized(collection) { 
   collection.clear(); 
}

synchronized(collection) {
   lines.stream().forEach(System.out::println);
}

这将确保访问collection对象时的线程安全,因为线程将需要在执行任何更新之前将监视器保存在实例collection上。

另外,正如@Holger所指出的,这样做:

synchronized(collection) {
   collection.add(line);
}
© www.soinside.com 2019 - 2024. All rights reserved.