Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

A crawler starts with one seed task; each task may spawn more tasks, and the main thread must wait until all tasks finish. Describe how to use a Phaser for this.

We create the Phaser with the main thread registered as one party, call phaser.register() before submitting each task, and have each task call arriveAndDeregister() in a finally block. A task that discovers new links registers and submits them before it deregisters itself, so the count of unfinished work never touches zero too early. The main thread submits the seed and calls arriveAndAwaitAdvance(), which returns when every task has finished. A single Phaser allows at most 65,535 parties registered at once, so very large crawls can use tiered phasers or bound the number of tasks in flight.

Why this question is asked

A web crawler is the classic example of work that grows while it runs: we start with one page, every page reveals more pages, and nobody knows in advance how many there will be. That breaks CountDownLatch, which needs its count up front, and CyclicBarrier, which needs a fixed group. Interviewers like this question because the correct Phaser code is short, but one ordering detail decides whether it works or returns early. In this answer, we will see why the simpler tools do not fit, set up the Phaser, write the task, look closely at the ordering rule, and then cover the party limit and alternatives.

1Why a Latch or a Barrier Does Not Fit

A CountDownLatch must be created with its final count. For a crawl we would have to know the number of pages before starting, which is the very thing we are trying to find out. A CyclicBarrier needs a fixed number of parties that all meet; our tasks are short-lived and appear at different times, so there is no group to meet.

What we need is a counter of unfinished work that can go up whenever a task is created and down whenever one finishes, plus a way for the main thread to wait until it reaches zero. A Phaser's registered-party count is exactly that counter, and its phase advance is exactly that moment.

2Setting Up the Phaser and the Seed

The main thread registers itself as the first party in the constructor. That registration has one job: it keeps the phaser from advancing or terminating before the main thread is ready to wait, because the phase cannot advance while a registered party has not arrived.

Java
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor();
Set<URI> seen = ConcurrentHashMap.newKeySet();
Phaser phaser = new Phaser(1); // party 1: the main thread
void submit(URI url) {
if (!seen.add(url)) return; // already crawled or queued
phaser.register(); // count this task BEFORE it can run
pool.submit(() -> crawl(url));
}
// main thread
submit(URI.create("https://example.com/")); // the seed
phaser.arriveAndAwaitAdvance(); // waits until every task has deregistered
System.out.println("crawled " + seen.size()); // crawled 1342, say
pool.close();

Notice that submit() registers before it hands the task to the pool. If it registered inside the task instead, the task might not have started yet when the count is checked, and the phaser would not know the task exists.

3The Task: Spawn Children, Then Deregister in finally

Each task fetches its page, finds links, submits each new link as a child task, and then signals that it is finished. The signal goes in a finally block, so a page that fails to download still counts as finished.

Java
void crawl(URI url) {
try {
Page page = fetcher.fetch(url); // may throw on a bad page
for (URI link : page.links()) {
submit(link); // registers the child first
}
} catch (Exception e) {
log.warn("failed {}", url, e); // record and carry on
} finally {
phaser.arriveAndDeregister(); // this task is done, its children are already counted
}
}

arriveAndDeregister() does two things at once: it records an arrival for the current phase and removes this task from the registered parties. When the last task finishes, the only registered party left is the main thread, which has already arrived, so arrived equals registered, the phase advances, and arriveAndAwaitAdvance() in the main thread returns.

4Why the Order Matters: Never Reaching Zero Too Early

The rule that makes this correct is that a task registers all its children before it deregisters itself. Think of the registered count as the number of unfinished tasks plus the main thread. When a task with three new links finishes, the count goes up by three, then down by one. It never drops to the point where only the main thread is left while work still exists.

Now imagine the wrong order: the task deregisters first and then submits its children. For a moment, the parent is gone and the children are not yet counted. If this was the only task running, arrived now equals registered, and the main thread is released while three pages are still waiting to be crawled. The bug is intermittent, because it depends on timing, which makes it hard to find in tests.

Step throughCounting work as the crawl grows
MainPhaserSeed taskChild tasks
new Phaser(1): registered 1
register() for seed: registered 2
arriveAndAwaitAdvance(): arrived 1 of 2
register() x3 for children: registered 5
arriveAndDeregister(): registered 4
each child arriveAndDeregister(): registered 1
arrived 1 of 1: phase advances
arriveAndAwaitAdvance() returns

8 messages in order. Play them, or step through them one at a time.

Children are registered before the parent leaves, so the count never reaches the main thread alone too early.

5The Party Limit and Tiered Phasers

A single Phaser can hold at most 65,535 registered parties at the same time; registering one more throws IllegalStateException. Notice that the limit is about tasks registered at once, not the total crawled: a crawl of a million pages is fine as long as no more than 65,535 tasks are pending together. But a crawler that submits every discovered link immediately can easily exceed that on a large site.

There are two ways out. Phasers can be tiered: new Phaser(parent) creates a child phaser that registers itself as a single party of its parent, so each child can hold its own 65,535 parties, and the tree also spreads contention across several counters. Or we can bound the work in flight, for example by putting discovered links into a queue and keeping only a few hundred tasks running, which is kinder to the sites we crawl anyway.

6Alternatives Worth Mentioning

The same counting idea can be written with an AtomicInteger of pending tasks and a CountDownLatch(1) that the last task opens, but then we must handle the ordering rule ourselves. ForkJoinPool also suits recursive tasks: each task can fork its children and join them, or the main thread can call awaitQuiescence on a pool used only for the crawl. The Phaser version has the advantage of being explicit and working with any executor, including virtual threads.

7Follow-up questions

Why does the main thread register itself instead of just calling awaitAdvance(0)?

Without the main party, the count could reach zero before the seed is even submitted, or right after it finishes and before the main thread starts waiting, and the phaser would terminate. Registering main keeps the phase open until main deliberately arrives. Alternatively main could call arriveAndDeregister() and then awaitAdvance(phase), but the registration at construction is still what prevents early termination.

What happens if a task throws without the finally block?

It never deregisters, so the count never reaches the main thread alone, and the main thread waits forever. That is why arriveAndDeregister() must be in finally, just like countDown() with a latch.

How would you add a timeout to the main wait?

Call int phase = phaser.arrive(); and then phaser.awaitAdvanceInterruptibly(phase, 10, TimeUnit.MINUTES), which throws TimeoutException if the crawl takes too long. Then shut down the pool with shutdownNow() to stop the remaining tasks.

8Conclusion

In this answer, we used a Phaser as a counter of unfinished work for a crawl that grows while it runs. The main thread registers itself in the constructor, every submission calls register() before the task can run, and every task calls arriveAndDeregister() in finally after registering its children, so the count never reaches zero too early. The main thread submits the seed and calls arriveAndAwaitAdvance() to wait for all tasks. We also saw that one phaser holds at most 65,535 parties at once, so very large crawls use tiered phasers or bound the tasks in flight.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that the amount of work isn't known up front, so a CountDownLatch doesn't fit, and there's no fixed group, so a CyclicBarrier doesn't either. A Phaser's registered-party count works as a counter of unfinished tasks.

Then, if they want more

I'd create it with new Phaser of one, so the main thread is a party, which stops it from advancing or terminating before main is ready. Then I'd have a submit method that calls phaser.register before handing the task to the executor, so the task is counted before it can possibly run.

Each task fetches its page, calls submit for every new link, and then calls arriveAndDeregister in a finally block, so even a failed page counts as done. The key ordering rule is that a task registers its children before it deregisters itself, so the count never drops to just the main thread while work still exists.

If you reversed it you'd get an intermittent early return. The main thread submits the seed and calls arriveAndAwaitAdvance, which returns when only main is left. One limit to mention is 65,535 parties registered at once on a single phaser.

For a big crawl I'd either use tiered phasers with a parent, or better, bound the tasks in flight with a queue.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A crawler starts with one seed task; each task may spawn more tasks, and the main thread...": https://scrivio-interview-library.netlify.app/java/synchronizers/bc54273b2b/