How to name the threads of a thread pool in Java

29,203

Solution 1

You can pass your own ThreadFactory to ScheduledThreadPoolExecutor. Your ThreadFactory will create thread and can give it any name you want. Your ThreadFactory can also reuse Executors.defaultThreadFactory(), and only change the name before returning the thread.

Solution 2

public class NamedThreadPoolExecutor extends ThreadPoolExecutor {

private static final String THREAD_NAME_PATTERN = "%s-%d";

    public NamedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, final TimeUnit unit,
                               final String namePrefix) {
       super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<>(),
            new ThreadFactory() {

                private final AtomicInteger counter = new AtomicInteger();

                @Override
                public Thread newThread(Runnable r) {
                    final String threadName = String.format(THREAD_NAME_PATTERN, namePrefix, counter.incrementAndGet());
                    return new Thread(r, threadName);
                }
            });
    }

}

Solution 3

From the ThreadPoolExecutor documentation:

Creating new threads New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks.

Share:
29,203
Sudarshan
Author by

Sudarshan

Sudarshan is a software professional with around 8 years experience in designing and developing enterprise Java applications. He has worked across a broad spectrum of technologies including but not limited to Mule ESB ( and it's surrounding technology stack), Spring, Hibernate, ZKOSS, Struts, Groovy, MongoDB and MySQL. He has exposure to the complete SDLC - architecture/design, building proof of concepts, development, unit and integration testing and early life production support. He is a certified MuleSoft Developer with a strong focus on analysis, design, development and implementation of EAI projects and sound knowledge of Message Integration Patterns. He has worked extensively on REST API design, development and management based on RAML specifications. His special interests include solution design, systems integration, Domain Driven Design, Command Query Responsibility Segregation (CQRS), Test Driven Development (TDD) and continuous integration. He is passionate about clean code and software craftsmanship - this passion delivers value to clients because clean code typically has fewer bugs than messy code and is less dearer to maintain. He is a strong advocate of a quality-oriented development environment (with CI, Sonar, automatic deployment, etc.)

Updated on March 01, 2020

Comments

  • Sudarshan
    Sudarshan about 4 years

    I have a Java application that uses the Executor framework and I have code that looks like this protected ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(5)

    My understanding is that internally the JVM would create a pool of 5 threads. Now when I check the execution in a profiler, I get something like thread-pool2,thread-pool3 and so on.

    Some of these thread pools are created by the server and some are created by me, I need a way to differentiate which were created by me and which were created by the server.

    I am thinking that if I can name the thread pools it should do the trick, however do not see any API which would allow me to do the same.

    Thanks in advance.

  • Joachim Sauer
    Joachim Sauer about 13 years
    If you're already using Guava, then its ThreadFactoryBuilder can make that pretty easy.
  • Peter Štibraný
    Peter Štibraný about 13 years
    @Joachim: ooh, very nice. I do use Guava, but I missed that class. Thank you!
  • Sudarshan
    Sudarshan about 13 years
    Is giving a name for a thread in the thread pool, same as naming the thread pool itself ?, I need to name the thread pool so that I can start seeing that name in the profiler :)
  • Peter Štibraný
    Peter Štibraný about 13 years
    @Sudarshan: thread pool itself has no name. Only threads do have names. Profiler is showing threads to you, not the pool.
  • Sudarshan
    Sudarshan about 13 years
    Yup just realized that Thanks :)
  • rogerdpack
    rogerdpack over 9 years
    For an example, see stackoverflow.com/a/6113794/32453