Creating Thread with Factory/Builder

Sometimes, you need to create many threads that share the same properties, like names, priorities, or exception handlers. Java provides tools to make this easier: ThreadFactory and Thread.Builder.

ThreadFactory

A ThreadFactory is an interface with a single method:

Thread newThread(Runnable r)

This method creates a new thread that will run the code in the given Runnable.

You can make your own class that implements ThreadFactory, or you can use a builder to create factories easily (Java 21 and later).

Thread Builders

Thread builders let you configure threads before creating them. Java provides two types of builders:

You can set different properties for the threads you build. For example:

Thread.Builder builder = Thread.ofVirtual().name("request-", 1);

This creates a builder that will name threads like request-1, request-2, etc. You can also customize:

Once your builder is ready, you can create threads in different ways:

Thread t1 = builder.unstarted(myRunnable);  // thread is created but not started
Thread t2 = builder.start(myRunnable);      // thread is created and starts immediately

Or you can make a ThreadFactory from the builder:

ThreadFactory factory = builder.factory();
Thread t3 = factory.newThread(myRunnable);  // creates a thread using the factory

Example:

Runnable task = () -> System.out.println("Running in thread: " + Thread.currentThread().getName());

Thread.Builder builder = Thread.ofVirtual().name("worker-", 1);

Thread t1 = builder.start(task);
Thread t2 = builder.start(task);

ThreadFactory factory = builder.factory();
Thread t3 = factory.newThread(task);
t3.start();

In this example:

Why Use Builders and Factories?

Reference: Thread API Methods