Card 01/ 08

ConceptDifficulty: Intermediate1 min

Work That Runs Beside Your Code Instead of After It

A report has to fetch four things from four services. Each call takes two seconds, none of them needs the others, and the report takes eight seconds because the code runs one line after another.

A thread is an independent path through your code. Your program already has one — the one main runs on — and creating a second means two lines of your program are being executed at the same moment.

java
Thread worker = new Thread(() -> {
    System.out.println("fetching");
    fetchRates();
});

worker.start();
System.out.println("main carries on");

start() is the line that creates a second path. It returns immediately, and from that moment two things are happening: the new thread runs the lambda, and main carries on to the next line without waiting.

So a thread buys you overlap, and the eight seconds become two. What it costs is that the order things happen in stops being the order they are written in, which is the subject of every other topic here.