正确使用ForkJoinPool提交并加入Java

时间:2018-09-16 17:18:05

标签: java multithreading forkjoinpool external-sorting

我最近在研究外部合并排序算法(External Sorting)的实现,而我的实现需要使用多线程方法。

我尝试使用ForkJoinPool,而不是使用Java中的Thread和ExecutorService等较旧的实现。该算法的第一步需要读取一个文件,并且每x行收集并发送以进行排序并写入文件。当主线程读取下一个批处理时,可以在单独的线程中执行此操作(排序和保存)。我已经写了一种方法来做到这一点(见下文)。

我担心的是,实际的并行工作不是在我使用ForkJoinPool.commonPool().submit(()->SortAndWriteToFile(lines, fileName))时开始,而是仅在循环结束后调用task.join()时才开始。那意味着在一个足够大的循环中,我将整理要运行的任务,但没有任何时间运行它们。当我使用invoke而不是submit时,似乎无法控制join的位置,也无法保证继续进行之前的所有工作。

有没有更正确的方法来实现这一目标?

我的代码如下。列出了该方法和两个实用程序方法。我希望这不会太长。

protected int generateSortedFiles (String originalFileName, String destinationFilePrefix) {

    //Number of accumulated sorted blocks of size blockSize
    int blockCount = 0;

    //hold bufferSize number of lines from the file
    List<String> bufferLines = new ArrayList<String>();

    List<ForkJoinTask<?>> taskList = new ArrayList<ForkJoinTask<?>>();

    //Open file to read
    try (Stream<String> fileStream = Files.lines(Paths.get(originalFileName))) {

        //Iterate over BufferSize lines to add them to list.
        Iterator<String> lineItr = fileStream.iterator();

        while(lineItr.hasNext()) {

            //Add bufferSize lines to List
            for (int i=0;i<bufferSize;i++) {
                if (lineItr.hasNext()) {
                    bufferLines.add(lineItr.next());
                }
            }

            //submit the task to sort and write to file in a separate thread
            String fileName= destinationFilePrefix+blockCount+".csv";
            List<String> lines = Collections.unmodifiableList(bufferLines);
            taskList.add(ForkJoinPool.commonPool().submit(
                    ()->SortAndWriteToFile(lines, fileName)));

            blockCount++;
            bufferLines = new ArrayList<String>();
        }
    } catch (IOException e) {
        System.out.println("read from file " +originalFileName + "has failed due to "+e);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("the index prodived was not available in the file "
                +originalFileName+" and the error is "+e);
    }
    flushParallelTaskList(taskList);

    return blockCount;
}

/**
 * This method takes lines, sorts them and writes them to file
 * @param lines the lines to be sorted
 * @param fileName the filename to write them to
 */
private void SortAndWriteToFile(List<String> lines, String fileName) {
    //Sort lines
    lines = lines.stream()
            .parallel()
            .sorted((e1,e2) -> e1.split(",")[indexOfKey].compareTo(e2.split(",")[indexOfKey]))
            .collect(Collectors.toList());

    //write the sorted block of lines to the destination file.      
    writeBuffer(lines, fileName);

}

/**
 * Wait until all the threads finish, clear the list
 * @param writeList
 */
private void flushParallelTaskList (List<ForkJoinTask<?>> writeList) {
    for (ForkJoinTask<?> task:writeList) {
        task.join();
    }
    writeList.clear();

}

0 个答案:

没有答案
相关问题