Skip to content
javahacks.dev
Concurrency

Java ThreadFactory Usage to Name Your Threads Clearly

Write a ThreadFactory that names threads, sets daemon status and an uncaught exception handler, so dumps and logs show which pool a thread is in.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, Linux, IntelliJ IDEA and Spring logos.

When a production service hangs, the first look is a thread dump. A dump full of pool-7-thread-3 tells you nothing. A name like orders-worker-3 points at the code.

The default

java
ExecutorService pool = Executors.newFixedThreadPool(4);

The default factory names threads pool-N-thread-M, where N counts pools created in the JVM. The number changes with startup order, so the name does not identify anything stable. Logs show it in %t patterns, and profilers group by it.

A custom factory

java
public final class NamedThreadFactory implements ThreadFactory {
    private final String prefix;
    private final boolean daemon;
    private final AtomicInteger counter = new AtomicInteger(1);

    public NamedThreadFactory(String prefix, boolean daemon) {
        this.prefix = prefix;
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable task) {
        Thread thread = new Thread(task, prefix + "-" + counter.getAndIncrement());
        thread.setDaemon(daemon);
        thread.setUncaughtExceptionHandler((t, e) ->
                LoggerFactory.getLogger(prefix).error("uncaught in {}", t.getName(), e));
        return thread;
    }
}
java
ExecutorService pool = Executors.newFixedThreadPool(4, new NamedThreadFactory("orders-worker", false));

Now a dump shows orders-worker-1 to orders-worker-4. The AtomicInteger makes the numbering safe when several threads are created at once, see atomic counters.

Without a custom class

From JDK 21, the builder API makes this a single expression:

java
ThreadFactory factory = Thread.ofPlatform()
        .name("orders-worker-", 1)       // prefix and starting counter
        .daemon(false)
        .uncaughtExceptionHandler((t, e) -> log.error("uncaught in {}", t.getName(), e))
        .factory();

For virtual threads, Thread.ofVirtual().name("fetch-", 0).factory() gives named virtual threads. Virtual threads have an empty name by default, which makes dumps harder to read, so name them.

Why the handler matters

A task submitted with submit stores its exception in the Future. A task submitted with execute that throws kills the thread, and the exception goes to the uncaught handler, which by default prints a stack trace to System.err. In a service that logs to a file, that output is easy to miss. Installing a handler routes it to the logger:

java
executor.execute(() -> { throw new IllegalStateException("boom"); });

With the handler above, the log line contains the thread name and the stack trace, and the pool replaces the dead thread.

Naming rules that work

  • Name per pool, number per thread. payments-io-3, not payments-io-order-4711. Thread names are set once at creation.
  • Do not rename inside tasks for per-request context. A thread-per-task rename leaks information and confuses dumps. Use MDC or ScopedValue for request context.
  • Keep prefixes short and consistent with the logger name or component.

Daemon or not

Daemon threads do not keep the JVM alive. Use true for housekeeping that should not block exit and false for work that must finish, as discussed in shutting down executors.

Frameworks

Spring's ThreadPoolTaskExecutor has setThreadNamePrefix("orders-"), and Guava has ThreadFactoryBuilder. Libraries like Netty and Tomcat name their threads with a clear prefix, such as http-nio-8080-exec-7, a style worth copying. The same names appear in the request log and help trace a slow request, per debugging with logs.

See the difference in a program

Names matter in exactly one place: the moment something is wrong and you are reading a thread dump or a log line. The program below shows the default name, a custom name from a factory, and what the handler catches. It ran on Eclipse Temurin 25.0.5.

Names.javajava
ExecutorService plain = Executors.newFixedThreadPool(1);
plain.submit(() -> System.out.println("default name : " + Thread.currentThread().getName())).get();

AtomicInteger n = new AtomicInteger(1);
ThreadFactory named = r -> {
    Thread t = new Thread(r, "invoice-worker-" + n.getAndIncrement());
    t.setUncaughtExceptionHandler((th, e) -> System.out.println("handler saw   : " + th.getName() + " died with " + e));
    return t;
};
ExecutorService pool = Executors.newFixedThreadPool(2, named);
pool.submit(() -> System.out.println("custom name  : " + Thread.currentThread().getName())).get();
pool.execute(() -> { throw new IllegalStateException("render failed"); });          // reaches the handler
Future<?> f = pool.submit(() -> { throw new IllegalStateException("render failed"); });   // stored in the Future
try { f.get(); } catch (ExecutionException e) { System.out.println("submit stored : " + e.getCause()); }
Text
default name : pool-1-thread-1
custom name  : invoice-worker-1
submit stored : java.lang.IllegalStateException: render failed
handler saw   : invoice-worker-2 died with java.lang.IllegalStateException: render failed

The default pool-1-thread-1 says nothing about what the thread does, and the pool number depends on the order pools were created in this run, so it changes between runs. invoice-worker-1 identifies the owner and the job. The last two lines show a distinction that surprises people: an exception thrown by a task given to execute kills the worker and reaches the uncaught exception handler, while the same exception thrown from a task given to submit is captured in the Future and reaches nobody unless get() is called. If you use submit and never read the future, the failure vanishes.

Without a handler installed the JVM prints the default:

Text
Exception in thread "pool-2-thread-1" java.lang.IllegalStateException: no handler installed
	at Names.lambda$main$8(Names.java:28)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)

That goes to standard error, not to your logging framework, so it is missed in a production setup that collects logs from a file. A handler that logs through the application's logger fixes that.

The builder API in JDK 21 and later

Writing a ThreadFactory class for naming is no longer necessary. The builders produce a factory in a line.

java
ThreadFactory workers = Thread.ofPlatform()
        .name("invoice-worker-", 1)                 // counter starts at 1
        .daemon(false)
        .uncaughtExceptionHandler((t, e) -> log.error("thread {} died", t.getName(), e))
        .factory();

ExecutorService pool = Executors.newFixedThreadPool(4, workers);
Thread poller = Thread.ofVirtual().name("report-", 1).unstarted(() -> runReport());

The name with a start counter produces invoice-worker-1, invoice-worker-2 and so on. For virtual threads the same builder works, and a name is even more useful because the default for a virtual thread is the empty string, so unnamed ones are invisible in dumps.

Choose names that survive a dump

A thread dump of a service can contain hundreds of threads, and the dump tool sorts them by name. Put the role first and the instance last: http-nio-8080-exec-7 and db-pool-3 group neatly, while thread-7 and worker do not. Include the component, not the class: ledger-sync-2 is a job that someone will search for. Avoid putting identifiers that change per task in the name of a pooled thread, such as a request id, because the name is reused for the next task; use the mapped diagnostic context in logs for that.

Daemon or not

A non-daemon thread keeps the JVM alive. A pool of non-daemon workers prevents shutdown until it is closed, as the executor shutdown post demonstrates. Mark background helpers that must never block exit, such as a cache refresher or a metrics reporter, as daemon threads. Mark the workers doing real work as non-daemon, and shut them down explicitly, so a JVM exit waits for in-flight tasks instead of cutting them off.

Monitor the pool by name

Names pay off most when pool statistics are exported. A metrics library tags each executor with its name, so a dashboard shows invoice-worker with its queue depth and active count next to report and http. With Micrometer, wrap the executor once and the metrics appear tagged with the name you give.

java
ExecutorService invoices = ExecutorServiceMetrics.monitor(
        registry, Executors.newFixedThreadPool(4, workers), "invoice-worker");

The metric names executor.active, executor.queued and executor.completed then carry name=invoice-worker. Alert on queued tasks that keep growing and on an active count equal to the pool size for minutes. Those two graphs, per named pool, answer the first question of every incident: which pool is the bottleneck. With default names the same question needs a thread dump and a guess.

Where this does not apply

A one-off executor in a test does not need a factory, but a service pool always does. For thread priority and thread groups, avoid both, because they have little effect on modern schedulers. The reference is the [ThreadFactory Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ThreadFactory.html), and the [Thread.Builder Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.Builder.html) covers the builders.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.