How to give name to a callable Thread? [duplicate] How to give name to a callable Thread? [duplicate] multithreading multithreading

How to give name to a callable Thread? [duplicate]


I'm currently doing it somewhat like this:

    someExecutor.execute(new Runnable() {        @Override public void run() {            final String orgName = Thread.currentThread().getName();            Thread.currentThread().setName(orgName + " - My custom name here");            try {                myAction();            } finally {                Thread.currentThread().setName(orgName);            }        }    });


You may use the overloaded method:

java.util.concurrent.Executors.newCachedThreadPool(ThreadFactory)

which allows you to pass a

java.util.concurrent.ThreadFactory

that should allow you to set the thread's names via java.util.concurrent.ThreadFactory.newThread(Runnable):

Constructs a new Thread. Implementations may also initialize priority, name, daemon status, ThreadGroup, etc.

Have a look at java.util.concurrent.Executors.DefaultThreadFactory for a default implementation.

Addendum

Since I see that this thread is still visited, Guava (if you have it available) provides a ThreadFactoryBuilder that leverages the need of having an inner anonymous class and even allows for customizing parametrized names for your threads.


/** * The default thread factory */static class DefaultThreadFactory implements ThreadFactory {    static final AtomicInteger poolNumber = new AtomicInteger(1);    final ThreadGroup group;    final AtomicInteger threadNumber = new AtomicInteger(1);    final String namePrefix;    DefaultThreadFactory() {        SecurityManager s = System.getSecurityManager();        group = (s != null)? s.getThreadGroup() :                             Thread.currentThread().getThreadGroup();        namePrefix = "pool-" +                       poolNumber.getAndIncrement() +                      "-thread-";    }    public Thread newThread(Runnable r) {        Thread t = new Thread(group, r,                               namePrefix + threadNumber.getAndIncrement(),                              0);        if (t.isDaemon())            t.setDaemon(false);        if (t.getPriority() != Thread.NORM_PRIORITY)            t.setPriority(Thread.NORM_PRIORITY);        return t;    }}

This is the original implementation in Java 1.5.0. So, you actually have the names as pool-x-thread where x stands for the order of the thread in the current thread group.