10

I'm using an ExecutorService to execute some Callables, but the name of the threads are like fixed-pool-1-thread-1.

How I change the name of the threads? If it's not possible, there another way to execute Callables that I can set the name of threadS?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199

3 Answers3

16

You'll have to use an ExecutorService implementation that allows you to set the ThreadFactory1 used to create threads, for example, ThreadPoolExecutor. Pass an instance that creates threads with the proper names.

There's also a handy class in commons-lang that allows to specify thread names with a pattern: BasicThreadFactory. This keeps you from having to create a ThreadFactory subclass just to provide the naming behavior.

Edward Dale
  • 29,597
  • 13
  • 90
  • 129
7

Guava almost always has what you need. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build() and pass it off to your ExecutorService.

Tim Frey
  • 9,901
  • 9
  • 44
  • 60
pathikrit
  • 32,469
  • 37
  • 142
  • 221
4

A quick and dirty way;

public void run() {
    Thread.currentThread().setName(aName);
    doStuff();
}
Kirk
  • 749
  • 1
  • 7
  • 10