Live coding puzzles question 173 of 180 mid
Make three tasks run concurrently but print their results in a fixed order.
- Run them sequentially
- Correct: Compute in parallel, then order the output with latches or by index
- Use thread priorities
- Synchronize on a shared lock
Two good answers, and picking the right one depends on whether the printing itself must be ordered or only the final output.
If you only need ordered output, do not coordinate at all: submit the tasks, collect the futures and print them in order. The work overlaps, the printing is sequential, and there is no shared state.
If each stage must print before the next begins, chain latches: task N counts down latch N, and task
N+1 awaits it first. CompletableFuture.thenRun expresses the same chain more readably. The mistake to
avoid is a shared volatile int turn with a spin loop, which burns a core to save a latch.