How to give name to a callable Thread?

user381878 picture user381878 · Jul 12, 2010 · Viewed 70.4k times · Source

I am executing a Callable Object using ExecutorService thread pool. I want to give a name to this thread.

To be more specific, in older version I did this -

Thread thread = new Thread(runnable Task);
thread.setName("My Thread Name");

I use thread name in log4j logging, this helps a lot while troubleshooting. Now I am migrating my code from Java 1.4 to Java 1.6. I have written this(Given below)- but I dont know how to give name to this thread.

private final ExecutorService executorPool = Executors.newCachedThreadPool();
Future<String> result = executorPool.submit(callable Task);

Please give me some idea to give name to this thread?

Answer

Bart van Heukelom picture Bart van Heukelom · Feb 28, 2011

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);
            }
        }
    });