0

For my Android application, I use ScheduledThreadPoolExecutor instead of Timer because it is not affected by time changes.

With the Timer, you can create it by giving it a name. EX: Timer myTimer = new Timer("TimerA");

This is very convenient because when debugging using DDMS in the Threads view, I can see which exactly Threads are running... and use the name to trace back to my code.

However, using ScheduledThreadPoolExecutor, I can't seem to give it a name. And so when debugging using Threads view in DDMS, I see something like: "pool-4-thread-1" which isn't meaningful and I can't trace back to my code with a name like that.

Can anyone help me with this?

yorkw
  • 40,926
  • 10
  • 117
  • 130
user657178
  • 213
  • 1
  • 3
  • 7

1 Answers1

2

The standard Java API doesn't support naming ThreadPoolExecutor, however, naming the Thread created by ThreadPoolExecutor is supported via ThreadFactory, check out here:

Creating new threads

New threads are created using a ThreadFactory. If not otherwise specified, a defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks.

Sample code:

ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = Executors.newScheduledThreadPool(5, new ThreadFactory() {
  final AtomicInteger threadNumber = new AtomicInteger(1);
    
  @Override
  public Thread newThread(Runnable r) {
    return new Thread(r, "Foo-" + threadNumber.getAndIncrement());
  }
});

Hope this helps.

Community
  • 1
  • 1
yorkw
  • 40,926
  • 10
  • 117
  • 130