Stop 12 · Multithreading & JVM InternalsProjects · 1/1

Multithreaded File Processor

Part of the Java Roadmap

In short

This project puts the whole phase to work: a thread pool, Callables, Futures, thread-safe results and a timing comparison. It is a small, honest way to show you understand concurrency.

A program that processes many log or CSV files in parallel using an ExecutorService, combines the results safely and reports the total time against a single-threaded version.

The jaadu, as a supervisor, hands bundles of paper to several examiners at long tables who check them side by side, while a tally board fills up at the front.

Think of it like this

Exam copies at the board office

A board office in Lucknow has thousands of answer sheets. One examiner would take months. Instead the sheets are split into bundles, eight examiners check bundles at the same time, and a supervisor adds up the marks at the end. Your program does the same with log files.

The big ideas

What you need to know

Split the work

Independent units like files are perfect for parallelism because they share no state.

Merge, don't share

Let each task return its own result and combine them at the end. That avoids locks entirely.

Measure honestly

Use System.nanoTime(), warm up once and run several times. Disk speed can limit the gains.

Handle failures

One unreadable file should be logged and skipped, not crash the whole run. Catch ExecutionException per Future.

How it works

Build it step by step

  1. 1

    List files

    Use Files.list or Files.walk to find every .log file in a folder.

  2. 2

    One task per file

    Wrap each file in a Callable<Map<String, Long>> that counts ERROR, WARN and INFO lines.

  3. 3

    Run in a pool

    Submit all tasks to a fixed pool sized to the number of cores, or virtual threads.

  4. 4

    Merge safely

    Combine results on the main thread from the Futures, so no shared mutable map is needed.

  5. 5

    Compare timing

    Run the same job single-threaded and print both times in a small table.

See it in code

Walk through the code

java
1import java.nio.file.*;2import java.util.*;3import java.util.concurrent.*;4import java.util.stream.*;5 6public class LogProcessor {7    public static void main(String[] args) throws Exception {8        List<Path> files;9        try (Stream<Path> s = Files.list(Path.of("logs"))) {10            files = s.filter(p -> p.toString().endsWith(".log")).toList();11        }12 13        long start = System.nanoTime();14        Map<String, Long> total = new TreeMap<>();15        int cores = Runtime.getRuntime().availableProcessors();16 17        try (ExecutorService pool = Executors.newFixedThreadPool(cores)) {18            List<Future<Map<String, Long>>> futures = files.stream()19                .map(f -> pool.submit(() -> countLevels(f)))20                .toList();21            for (Future<Map<String, Long>> fut : futures) {22                try {23                    fut.get().forEach((k, v) -> total.merge(k, v, Long::sum));24                } catch (ExecutionException e) {25                    System.err.println("Skipped a file: " + e.getCause());26                }27            }28        }29        System.out.printf("%s in %d ms%n", total, (System.nanoTime() - start) / 1_000_000);30    }31 32    static Map<String, Long> countLevels(Path file) throws Exception {33        try (Stream<String> lines = Files.lines(file)) {34            return lines.map(l -> l.split(" ", 3))35                        .filter(parts -> parts.length > 1)36                        .collect(Collectors.groupingBy(parts -> parts[1], Collectors.counting()));37        }38    }39}

1/4List the .log files, closing the directory stream with try-with-resources.

Assumes lines like "2026-11-02 ERROR Payment failed". Each file is counted on its own thread and merged on main.

Save yourself the pain

Common mistakes

Oops

Having every thread write into one shared HashMap.

Do this instead

HashMap is not thread-safe. Return per-file results and merge them, or use ConcurrentHashMap.merge.

Oops

Creating one platform thread per file for 50,000 files.

Do this instead

Use a bounded pool, or virtual threads, so the machine isn't flooded with threads.

Oops

Reporting a 10x speed-up from a single run.

Do this instead

Run each version a few times, and mention that disk I/O and file size affect the result.

Your mission

Ship the project

~120 min

Quick check

Why does the example merge results on the main thread instead of sharing one map across tasks?

Go deeper

  1. 1Submit one task per file to a fixed thread pool and collect Futures.
  2. 2Merge per-file results with a ConcurrentHashMap or by combining returned values.
  3. 3Compare run times with 1, 2, 4 and 8 threads and explain the results.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge