Quick revision
The short answer
A ThreadFactory implements newThread(Runnable r): we create the thread, name it with a prefix and an AtomicInteger counter, such as orders-worker-1, and call setUncaughtExceptionHandler() with a handler that logs the thread name and the exception. Guava's ThreadFactoryBuilder or, since Java 21, Thread.ofPlatform().name("orders-worker-", 0).factory() do the same with less code. Readable names make thread dumps, logs and profiles understandable during incidents, but remember that tasks given to submit() store their exceptions in the Future, so the handler only sees exceptions from execute().
What to remember
In this answer, we wrote a ThreadFactory that names threads with a prefix and an AtomicInteger counter, sets daemon status explicitly and installs an uncaught exception handler that logs with our logger. We saw the shorter versions with Guava's ThreadFactoryBuilder and Thread.ofPlatform().name(...).factory() on Java 21, why names make thread dumps, logs and profiles readable during incidents, and that tasks given to submit() store their exceptions in the Future, so the handler only sees exceptions from execute().
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A ThreadFactory implements newThread(Runnable r): we create the thread, name it with a prefix and an AtomicInteger counter, such as orders-worker-1, and call setUncaughtExceptionHandler() with a handler that logs the thread name and the exception. Guava's ThreadFactoryBuilder or, since Java 21, Thread.ofPlatform().name("orders-worker-", 0).factory() do the same with less code. Readable names make thread dumps, logs and profiles understandable during incidents, but remember that tasks given to submit() store their exceptions in the Future, so the handler only sees exceptions from execute().
Background to this question
Every executor in a service creates threads, and by default they are called pool-1-thread-1, pool-2-thread-1 and so on, which tells us nothing during an incident. Exceptions that kill a thread go to standard error, which may never reach our logs. A ThreadFactory is the hook that fixes both, and writing one is a common coding question because it is short but has a few traps. In this answer, we will recap what a ThreadFactory does, write one by hand, look at the shorter versions with Guava and the Java 21 builder, see why names matter in a real thread dump, and finish with the submit() trap.
1A Quick Recap of ThreadFactory
ThreadFactory is an interface with a single method, Thread newThread(Runnable r). An executor such as ThreadPoolExecutor never calls new Thread() itself; whenever it needs a worker, it asks its factory. The Runnable it passes is the worker loop that will pull tasks from the queue, not one of our tasks. So the factory decides everything about the threads a pool uses: name, daemon status, priority and uncaught exception handler. Executors.defaultThreadFactory() names threads pool-N-thread-M and sets none of the rest.
2Writing the Factory by Hand
Here is a factory for the order-processing pool. The counter is an AtomicInteger because several threads may ask the pool for new workers at the same time, and the handler logs with our logger rather than printing to System.err.
Notice that we set daemon status explicitly. Without that line, the thread inherits the daemon flag of whichever thread happened to trigger its creation, which makes pool behaviour depend on the caller. Notice also that the factory does not start the thread; the executor does that.
3Shorter Versions: Guava and the Java 21 Builder
Writing the class by hand is a good exercise, but in real code two shorter options exist. Guava's ThreadFactoryBuilder takes a name format with a %d placeholder. Since Java 21, Thread.ofPlatform() returns a builder, and name(prefix, start) gives every thread the prefix followed by a counter that starts at the given number.
In Spring, ThreadPoolTaskExecutor has setThreadNamePrefix("orders-worker-"), so a separate factory is only needed when we also want a custom handler.
4Why Names Matter During an Incident
During an incident, the first tools we reach for are a thread dump (jstack <pid> or jcmd <pid> Thread.print), a profiler and the logs, and all of them identify threads by name. Compare the two dumps below for the same stuck service.
| Tool | With default names | With named threads |
|---|---|---|
| Thread dump | pool-3-thread-7 parked | orders-worker-7 parked |
| Log line | [pool-3-thread-7] ERROR | [orders-worker-7] ERROR |
| Profiler | CPU in pool-3-* | CPU in orders-worker-* |
| Thread count metric | Cannot be grouped | Grouped by prefix |
With the second name, we know at once that all eight order workers are parked, and we can look at the order pool's queue and its dependencies. Logback's %thread pattern puts the same name into every log line, so we can filter the logs to one component. Profilers group CPU samples by thread name, which shows which pool is burning CPU. A name costs one line of code and saves minutes when minutes matter.
5The Trap: submit() Never Reaches the Handler
The uncaught exception handler only runs when an exception escapes a thread's run() method. With execute(), our task runs directly in the worker, so its exception escapes and the handler logs it. With submit(), the executor wraps our task in a FutureTask, which catches the exception and stores it in the returned Future. The worker sees a task that completed normally, and the handler is never called.
So for fire-and-forget work we either use execute(), catch and log inside the task, or override ThreadPoolExecutor.afterExecute() to inspect completed futures. The factory's handler is a safety net for raw threads and execute(), not a replacement for handling task errors.
6Follow-up questions
Why does the pool replace a thread after an uncaught exception?
Because the exception ended the worker's run loop, so that thread is finished. ThreadPoolExecutor notices the worker died and creates a new one through the factory, which is why counters in names keep increasing on a pool that has failing tasks, a useful signal in itself.
Should a ThreadFactory set thread priority?
Usually not. Priorities are hints that HotSpot ignores on Linux by default, and virtual threads ignore them entirely. Name, daemon status and the exception handler are the properties that matter.
Can we name virtual threads the same way?
Yes. Thread.ofVirtual().name("orders-", 0).factory() gives a factory, and Executors.newThreadPerTaskExecutor(factory) uses it. Virtual threads have an empty name by default, so naming them is just as useful in thread dumps.
7Conclusion
In this answer, we wrote a ThreadFactory that names threads with a prefix and an AtomicInteger counter, sets daemon status explicitly and installs an uncaught exception handler that logs with our logger. We saw the shorter versions with Guava's ThreadFactoryBuilder and Thread.ofPlatform().name(...).factory() on Java 21, why names make thread dumps, logs and profiles readable during incidents, and that tasks given to submit() store their exceptions in the Future, so the handler only sees exceptions from execute().
Open with
A ThreadFactory has one method, newThread, which the executor calls whenever it needs a worker. In mine I'd create the thread with a name like orders-worker- plus a counter from an AtomicInteger, since several threads can ask for workers at once.
Then, if they want more
I'd set daemon to false explicitly, so it doesn't inherit from whatever thread triggered creation, and call setUncaughtExceptionHandler with a lambda that logs the thread name and the exception through our logger instead of letting it go to standard error. Then I pass the factory to Executors.newFixedThreadPool or the ThreadPoolExecutor constructor.
In real code I'd probably not write the class: Guava's ThreadFactoryBuilder does it with a name format, and on Java 21 Thread.ofPlatform().name("orders-worker-", 0).uncaughtExceptionHandler(...).factory() does it without a dependency, and in Spring ThreadPoolTaskExecutor has setThreadNamePrefix. Why it matters: during an incident everything identifies threads by name.
A thread dump showing orders-worker threads all parked tells me immediately which component is stuck, while pool-3-thread-7 tells me nothing. The same names appear in log lines and profiles, and I can group thread counts by prefix.
One trap to mention: the handler only fires when an exception escapes run, so it catches failures from execute, but tasks passed to submit have their exception stored in the Future, and I need to handle that separately.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- 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.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 "Write a ThreadFactory for an order-processing pool that gives threads readable names and...": https://scrivio-interview-library.netlify.app/java/threads/ff4bdf50a9/