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.
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(); } }
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
:
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.ThreadFactory
created in line 8.for
loop that iterates 5
times. Each iteration submits a task to executorService
. The task prints the name of the thread executing it.executorService
is shut down.