Video in progress
You need to sort a 200 GB file on a server with 4 GB of memory. How do you do it?
External merge sort: I split the file into chunks that fit in memory, sort each one and write it to disk, then do a k-way merge of all the sorted chunks in a single pass using a min-heap. The main cost is disk I/O, so reducing the number of passes matters.
📖 Answer
Two phases.
- Creating runs. I read, say, 1-2 GB from the file, sort it in memory and write it to
run-0001.tmp. 200 GB gives roughly 100-200 runs. - K-way merge. I open a buffered reader for each run. The min-heap holds the current line of each run. I take out the smallest and write it, then add the next line from that same run to the heap.
record Head(String line, BufferedReader src) {}
static void merge(List<Path> runs, Path out) throws IOException {
PriorityQueue<Head> pq = new PriorityQueue<>(Comparator.comparing(Head::line));
for (Path p : runs) {
BufferedReader r = Files.newBufferedReader(p);
String l = r.readLine();
if (l != null) pq.add(new Head(l, r)); else r.close();
}
try (BufferedWriter w = Files.newBufferedWriter(out)) {
while (!pq.isEmpty()) {
Head h = pq.poll();
w.write(h.line()); w.newLine();
String next = h.src().readLine();
if (next != null) pq.add(new Head(next, h.src())); else h.src().close();
}
}
}
The code is simple; the pain is around it:
- Having 200 files open at once is usually not a problem, but each reader needs a buffer. 200 × 8 MB = 1.6 GB. If there are too many runs, I do the merge in two stages.
- If you turn 1 GB of text into
Strings, it takes 2-3 times more space on the heap (object headers, arrays). I choose the run size accordingly, otherwise you get anOutOfMemoryError. - On an HDD, random reads are disastrous; large buffers make the reads sequential.
- Compressing the temporary files with LZ4 spends CPU to win on I/O, which is usually worth it.
- If the process crashes at hour 3, don't start from zero: leave the finished runs on disk and continue from them when it restarts.
Before all that, I ask one question: do we really need a full ordering? Often the goal is "find duplicates" or "group by key". In that case, partitioning by hash into 256 files and processing each in memory is much cheaper. If it's a one-off job, Unix sort does exactly this algorithm; there's no need to write Java.
Sign up to mark studied questions and save your progress.