views:

143

answers:

2

Hi Guys,

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?

+1  A: 

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.

Andreas
ThreadFactory.newThread(runnable), but my task is Callable...!
Your `Callable` will be wrapped into a `java.util.concurrent.FutureTask` that implements `java.util.concurrent.RunnableFuture` that implements `Runnable`. On the other hand it wouldn't make much sense that `ThreadFactory` allows the thread creation only for `Runnable`s whereas `ExecutorService` allows the submission of `Callable`s.
Andreas
thanks for your suggestion - I have found another alternative to do that-I am putting this as first line of my thread -Thread.currentThread().setName(this.client.getIdentityString());
@user381878, You should heed the warning given by @Shai. Your Callable does not own the Thread it is running on in an ExecutorService. Unless every single Callable and Runnable you submit first changes the Thread's name, then you will eventually get inconsistent logs.
Tim Bender
+2  A: 

You should be careful when renaming threads when your threads are managed by a thread-pool because they are actually being reused over and over again for different tasks and once renamed, you might find that the thread names in your logs don't make any sense... In order to avoid that unwanted behavior you should make sure that once your Runnable/Callable finished the thread name is restored.

One way to implement this is by wrapping every Runnable/Callable that is executed by the thread-pool with a decorator which handles all of the needed clean-ups.

Shai