【问题标题】:Use of join method in CompletableFuture class vs get method在 CompletableFuture 类中使用 join 方法与 get 方法
【发布时间】:2019-02-13 03:53:34
【问题描述】:

我想实现一个功能,将一个大文件分解成多个块并且可以并行进行处理。

我使用 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】:

    原因是这样的:

    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);
    }
    

    【讨论】:

    • 完美。你是上帝派来的。收集清楚是坏人。我真的很感激有关同步的附加信息。我也会实现的
    • @user1906450 乐于助人!
    • @user1906450 它对你有用吗?如果这样做,其他人也可以受益,你能接受我的回答吗?
    • 它是 synchronized,末尾有一个 d。此外,它只会提供互斥,它不保证forEach 操作将在clear 之前运行。由于forEach 也可以在clear 之后运行,因此您也必须使用synchronized 保护add 操作,而不是它会修复语义错误。最后,可以通过为每个块创建一个新的ArrayList 轻松修复代码,因此不会同时访问任何对象,也不需要synchronized
    • @Holger 那是我的错,用synchronized 打错了。对于synchronized,我的意图是只防止并发访问。我同意不能保证明确不执行第一个,因为调度程序会决定。不过,考虑到将要进行的工作量,我真的觉得创建 ArrayList 的副本应该是最后的手段。欢迎您通过一些解决方法来编辑我的答案!
    猜你喜欢
    • 2018-01-11
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多