I've worked recently on an implementation of a external merge sort algorithm (External Sorting) and my implementation needed to use a multi-threaded approach.
I tried to use ForkJoinPool instead of using the older implementations in Java such as Thread and ExecutorService. The first step of the algorithm requires to read a file, and every x lines collect and send to be sorted and written to file. This action (sort and save) can be done in a separate thread while the main thread reads the next batch. I've written a method to do just that (see below).
My concern is that the actual parallel work is not started when I use ForkJoinPool.commonPool().submit(()->SortAndWriteToFile(lines, fileName))
but instead only when I call task.join()
after the loop had finished. That would mean that on a large enough loop I'd be collating the tasks to be run, but not gaining any time running them. When I used invoke
instead of submit
it seems like I cannot control where the join
will be and cannot guarantee all the work was done before moving on.
Is there a more correct way to implement this?
My code is below. The method and two utility methods are listed. I hope this is not too long.
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();
}