Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A command-line batch job ends with exit code 0 but the last few hundred records are never written. Its main method calls CompletableFuture.runAsync(() -> writeBatch(batch)) for each batch and then returns. Explain and fix.

CompletableFuture.runAsync() without an executor runs the task on ForkJoinPool.commonPool(), whose worker threads are daemon threads. When main returns, no non-daemon thread is left, so the JVM exits with code 0 and abandons the batches still being written. The fix is to keep every future and call CompletableFuture.allOf(...).join() before main returns, or to use our own executor and shut it down and await termination, and in both cases to check the futures for failures so the exit code reports errors.

Why this question is asked

Batch jobs that report success while losing data are among the most expensive bugs to find, because nothing alerts. The scheduler sees exit code 0, the logs show no errors, and the missing records are discovered days later by someone reconciling numbers. Interviewers ask this question because it combines three things we must understand: which pool CompletableFuture uses by default, what a daemon thread is, and when the JVM decides to exit. In this answer, we will reproduce the problem, follow the JVM's exit decision, and then fix it two ways, including a correct exit code.

1A Quick Recap: Daemon Threads and the Common Pool

The JVM keeps running while at least one non-daemon thread is alive. Our main thread is non-daemon. A daemon thread is a background thread that the JVM does not wait for: when the last non-daemon thread ends, the JVM runs its shutdown hooks and halts, and any daemon threads stop wherever they are.

CompletableFuture.runAsync(Runnable) and supplyAsync(Supplier) have overloads that take an Executor. When we leave it out, the task runs on ForkJoinPool.commonPool(), a shared pool sized to the number of CPU cores minus one. Its worker threads are daemon threads, by design, so that background parallel work such as parallel streams never prevents a program from ending.

2Reproducing the Lost Records

Here is the job in a reduced form. Each batch takes a little time to write.

Java
public static void main(String[] args) {
List<List<Record>> batches = readBatches(); // 50 batches of 1,000 records
for (List<Record> batch : batches) {
CompletableFuture.runAsync(() -> writeBatch(batch)); // common pool, daemon threads
}
System.out.println("submitted"); // printed at once
} // main returns -> process exits with code 0
// Rows in the target table afterwards: 46,000 (it varies from run to run)

Notice that the loop only submits tasks; it does not wait for any of them. On an 8-core machine the common pool has 7 workers, so only 7 batches are in progress at a time and the rest wait in the pool's queues. When main returns a moment later, most of the work is done or queued, but some is not.

3Why the JVM Exits With Code 0

When main returns, the main thread ends. The JVM counts the remaining non-daemon threads and finds none, because the only threads doing work are common-pool workers, which are daemons. So it starts the shutdown sequence and halts. The workers are stopped mid-write and the queued batches are never started. Nothing throws, and no exception reaches main, so the exit code is 0.

The missing records are the last few hundred because the earlier batches had time to finish while main was still submitting. If the input grew or the database slowed down, the loss would grow too, which is why such bugs often appear only in production.

Step throughWhat happens when main returns
  1. main submits 50 batchesrunAsync with no executor
  2. Common pool workers start writingdaemon threads
  3. main returnsthe only non-daemon thread ends
  4. Any non-daemon threads alive?
    YesJVM keeps runningNoJVM begins shutdown
  5. Shutdown hooks run, JVM haltsworkers stop mid-batch, queued batches never run
  6. Exit code 0nothing threw on the main thread

6 steps in order. Play them, or step through them one at a time.

4Fix 1: Keep the Futures and Join Them

The smallest fix is to keep each CompletableFuture and wait for all of them before main returns. allOf() combines them into one future that completes when every one has completed, and join() blocks main until then.

Java
public static void main(String[] args) {
List<CompletableFuture<Void>> futures = readBatches().stream()
.map(b -> CompletableFuture.runAsync(() -> writeBatch(b)))
.toList();
try {
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
} catch (CompletionException e) {
long failed = futures.stream().filter(CompletableFuture::isCompletedExceptionally).count();
System.err.println(failed + " batches failed: " + e.getCause());
System.exit(1); // the scheduler sees the failure
}
System.out.println("all batches written");
} // exit code 0 only when every batch succeeded

Notice that join() throws CompletionException if any batch failed, but only after all of them have completed. That is exactly what we want for the exit code: we report the failure, with a count, and return a non-zero status so the scheduler can alert or retry.

5Fix 2: Use an Explicit Executor and Shut It Down

The common pool is shared with everything else in the JVM and sized for CPU work, while writing to a database is I/O. So for a real job it is better to give the work its own executor, which also lets us decide the concurrency deliberately, for example to match the database connection pool.

Java
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(8); // non-daemon threads
List<CompletableFuture<Void>> futures = readBatches().stream()
.map(b -> CompletableFuture.runAsync(() -> writeBatch(b), pool))
.toList();
pool.shutdown(); // accept no new tasks
if (!pool.awaitTermination(30, TimeUnit.MINUTES)) {
System.err.println("timed out");
pool.shutdownNow();
System.exit(2);
}
boolean anyFailed = futures.stream().anyMatch(CompletableFuture::isCompletedExceptionally);
System.exit(anyFailed ? 1 : 0);
}

The pool's threads are non-daemon, so even without awaitTermination() the JVM would not exit before the work finished. But relying on that alone still hides failures, so we wait explicitly and check every future. On Java 19 and later, an ExecutorService is AutoCloseable, and a try-with-resources block whose close() waits for the tasks is a shorter way to write the shutdown part.

6Making the Exit Code Tell the Truth

Both fixes share one rule: a batch job's exit code is its only reliable report to the scheduler. A failure inside an async task never reaches main by itself, so we must collect the outcomes and turn them into a non-zero status. It also helps to log a final summary such as 50 batches, 49 written, 1 failed, and to make writeBatch() idempotent, so a rerun after a failure does not duplicate the records that did succeed.

7Follow-up questions

Would a shutdown hook that waits for the common pool fix it?

It would be fragile. ForkJoinPool.commonPool().awaitQuiescence() can wait for running work, but hooks run during shutdown when other parts of the system may already be stopping, and the job still could not report failures through its exit code. Waiting in main before returning is simpler and correct.

Why is the common pool a poor choice for database writes even apart from the daemon problem?

It is sized for CPU-bound work, roughly one thread per core, and shared by parallel streams and every other default async call in the JVM. Blocking I/O on it starves other users and gives a concurrency level unrelated to what the database can handle. A dedicated, deliberately sized executor avoids both.

Would virtual threads avoid the problem?

No. Virtual threads are always daemon threads, so starting them from main without joining has the same effect. The fix is the same: wait for the tasks, for example by closing a newVirtualThreadPerTaskExecutor() in try-with-resources.

8Conclusion

In this answer, we saw that runAsync() without an executor uses the common pool, whose threads are daemons, so when main returns the JVM exits and abandons the batches in progress, still with exit code 0. We fixed it by joining all futures with allOf(...).join(), or by using a dedicated executor that we shut down and await. In both fixes we checked the futures for failures and turned them into a non-zero exit code, because that is the only signal the scheduler sees.

What to say in the interviewAbout 90 seconds aloud

Open with

The cause is the default executor. runAsync without an executor argument runs on ForkJoinPool.commonPool, and the common pool's worker threads are daemon threads. The JVM only waits for non-daemon threads, and main is the only one here.

Then, if they want more

So main submits all the batches and returns, the JVM sees no non-daemon threads left, runs shutdown hooks and halts. Whatever the workers were writing is cut off and queued batches never start.

Nothing threw on the main thread, so the exit code is zero, and the loss is usually the last batches because the early ones had time to finish.

The first fix is to keep the futures and call CompletableFuture.allOf on them and then join before main returns. join throws a CompletionException if any batch failed, so I catch it, log how many failed and call System.exit with a non-zero code.

The second fix, which I'd prefer for a real job, is to pass a dedicated executor sized for the database, then call shutdown and awaitTermination with a sensible timeout, and afterwards check every future for exceptional completion. That also gets database I/O off the common pool, which is meant for CPU work.

Either way, the key point is that the exit code has to reflect the async failures, because the scheduler can't see anything else.

About this answer

Last updated
12 November 2026
Versions it names
Java 19
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 command-line batch job ends with exit code 0 but the last few hundred records are...": https://scrivio-interview-library.netlify.app/java/threads/dd1bbb11da/