Friday, 24 June 2011

Naming threads created with the ExecutorService

When profiling applications it sometimes becomes a pain to understand where so many threads come from and what the hell they are doing.






If you’re like me and have a dependency on java.util.concurrent‘s API’s for anything concurrency-related, then you’ve certainly noticed that default thread names aren’t particularly helpful with the aforementioned problem.
Here’s a quick & dirty implementation of a ThreadFactory (based on Executors.DefaultThreadFactory) but with support for your own thread name prefixes.

public class NamedThreadFactory implements ThreadFactory {

// constants -----------------------------------------------------------------

private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);

// internal vars -------------------------------------------------------------

private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;

// constructors --------------------------------------------------------------

public NamedThreadFactory() {
this("ThreadPool(" + POOL_NUMBER.getAndIncrement() + "-thread-");
}

public NamedThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix + "(pool" +
POOL_NUMBER.getAndIncrement() + "-thread-";
}

// ThreadFactory -------------------------------------------------------------

public Thread newThread(Runnable r) {
Thread t = new Thread(this.group, r, this.namePrefix +
this.threadNumber.getAndIncrement() + ")", 0L);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
Tip: If you’re using Spring, you can just use CustomizableThreadFactory and save yourself the trouble.

No comments:

Post a Comment