Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name the threads of a thread pool in Java [duplicate]

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.

like image 933
Sudarshan Avatar asked Apr 21 '11 06:04

Sudarshan


2 Answers

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.

like image 197
Peter Štibraný Avatar answered Oct 04 '22 04:10

Peter Štibraný


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);                 }             });     }  } 
like image 42
Karol Król Avatar answered Oct 04 '22 02:10

Karol Król