When using a FutureTask having a Callable parameter, is it possible to set the name of the underlying Thread to a custom value?
It would be nice to assign a meaningful name to the Thread for log purposes.
The FutureTask/Callable isn't usually the place for naming the Thread. Rather, you could use a ThreadFactory parameter to either the Executors method you are using to generate your Thread Pool, or the constructor the Executor implementation you are using. The ThreadFactory would generate a Thread and provide a 'meaningful' name when asked to make a newThread().
Thank you Steve, that's what I was looking for.
I created an implementation of ThreadFactory and use it when retrieving the executor service like so:Cheers,
Kjeld
I was a little to fast being happy with this solution. Apparently the execute method of the executorservice does not guarantee a new thread to be created.
I noticed it reuses threads that are 'done'. What I was hoping for, is that the execute command would start a new thread with a custom name for that specific future task, and after the task is done, the thread would no longer be used.
Killing a thread apparently is not the way to go (because all appropriate methods are either not implemented or deprecated) so I tried using Thread.currentThread().join(), but since my main thread is waiting for these customized threads to finish, the main thread itself never finishes.
Yeah, the point of the ExecutorServices are to provide thread pools that can be shared to run tasks (less resources used by the computer than making lots of new threads for each task).
So if this isn't what you want, then I have to ask what you are really trying to do? Why do you need custom Thread names for each task? Why does it matter what thread a task is being run in?
If you need to / really want to change the Thread Name for each task, then as part of the run() method you would need to call Thread.currentThread().setName(...). Note that since the Thread is part of the pool, the name will persist until it gets renamed by another runnable, possibly causing confusion. So you might want to do something like this:
Thanks for your fast response.
Considering all this, it might not be wise to try and influence the thread names for this purpose.
What I am trying to do is start several future tasks to execute a asynchronous process. It is the same process being executed in different context.
The gain of have custom thread names was simply for logging purposes, it would have been convenient to distinguish processes by thread name.
Cheers,
Kjeld
Kjeld Sigtermans - SCJP 1.4 - SCWCD 1.4
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.