Video in progress
How do you process a 10 GB log file with a 512 MB heap?
You don't load the file into memory at all; you stream it line by line: BufferedReader.readLine() or Files.lines inside try-with-resources. Memory holds only the current line and the result (for example, counters).
📖 Answer
readAllLines or readString throws OutOfMemoryError here immediately. Even if the file looks like it would fit into the heap, as a String it takes up much more space.
The streaming approach:
Map<String, Long> byLevel = new HashMap<>();
try (Stream<String> lines = Files.lines(Path.of("/var/log/app.log"))) {
lines.map(l -> l.split(" ", 4))
.filter(p -> p.length > 2)
.forEach(p -> byLevel.merge(p[2], 1L, Long::sum));
}
Memory depends on the size of the result, not on the number of lines. The most common mistake here is collecting all the lines into a List and counting afterwards.
What to look at for speed:
- buffer size:
new BufferedReader(reader, 1 << 16)sometimes helps, but measure it; splituses regex; in hot loops, cutting by hand withindexOfis faster;- if you need parallelism,
Files.lines(...).parallel()does not split well. Splitting the file into byte ranges and reading each chunk with its ownFileChannelis more efficient, but you have to find the line boundary correctly.
If the file is gzip, GZIPInputStream also streams, so the solution doesn't change.
Sign up to mark studied questions and save your progress.