[ACCEPTED]-How to name the threads of a thread pool in Java-executorservice

Accepted answer
Score: 48

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

Score: 11
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);
                }
            });
    }

}

0

Score: 9

From the ThreadPoolExecutor documentation:

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

Score: 0

Use your own custom thread factory. Implement 5 a ThreadFactoryBuilder to create you custom 4 thread factories that allows you to do the 3 following:

  1. Have custom thread names
  2. Have choice of threads - User or Daemon threads
  3. Have choice of Thread Priority
  4. Have flexibility to set uncaught exception handlers

You have a sample ThreadFactoryBuilder 2 implementation in the following post which 1 you can use.

http://wilddiary.com/understanding-java-threadfactory-creating-custom-thread-factories/

More Related questions