How to give custom names to threads in ExecutorService in Java

Overview

ExecutorService is a JDK API that makes asynchronous task execution easier. ExecutorService offers a pool of threads and an easy-to-use API for assigning tasks. The ExecutorService gives the name of the threads in the thread pool. This shot discusses how we can assign custom names to the threads of the thread pool of the ExecutorService.

BasicThreadFactory

An ExecutorService employs a ThreadFactory to create its threads to execute tasks. In many circumstances, users do not need to worry about a ThreadFactory because the ExecutorService's default one will suffice. A custom ThreadFactory must be constructed with particular needs, such as thread naming.

BasicThreadFactory implements the ThreadFactory interface that provides specific configuration options for the threads it creates from the apache.commons.lang3 library.

Note: Refer to apache.commons.lang3 to add the commons-lang dependency to your project.

Code

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args){
        BasicThreadFactory factory = new BasicThreadFactory.Builder()
                .namingPattern("educative-thread-%d")
                .priority(Thread.MAX_PRIORITY)
                .build();

        ExecutorService executorService = Executors.newFixedThreadPool(3, factory);

        for(int i=0; i < 5; i++)
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));

        executorService.shutdown();
    }
}
Implementation of the BasicThreadFactory method

Explanation

We create a Maven project in the code above. The commons-lang dependency is added to the pom.xml file. Main.java is the file where the code is written.

The following is the explanation of the code in Main.java:

  • Lines 1–3: We import the relevant packages.
  • Lines 8–11: We create an instance of the BasicThreadFactory. We set the naming pattern priority of the threads created by the factory. The %d is used to differentiate different threads using an integer.
  • Line 13: We create a fixed thread pool of 3 threads with the ThreadFactory created in line 8.
  • Lines 15–16: We run a for loop that iterates 5 times. Each iteration submits a task to executorService. The task prints the name of the thread executing it.
  • Line 18: The executorService is shut down.

Free Resources