I just had to do what you are asking for -- providing names to my thread groups -- so thanks to Andeas's answer, I created my own ThreadFactory as an inner-class to the class that is going to use it by copying Executors$DefaultThreadFactory, changing 3 lines by adding the parameter "groupname" to the constructor.
/**
* A thread factory that names each thread with the provided group name.
*
* Except lines with "elarson modified", copied from code
* Executors$DefaultThreadFactory -- Doug Lea, Copyright Oracle, et al.
*/
static class GroupNameThreadFactory implements ThreadFactory {
private String groupname; /* elarson modified */
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
GroupNameThreadFactory(String groupname) {
this.groupname = groupname; /* elarson modified */
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
this.groupname + /* elarson modified */
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
Creating a ThreadPool from it is done as follows.
ThreadFactory threadfactory = new GroupNameThreadFactory("Monitor");
executor = Executors.newFixedThreadPool(NUM_THREADS, threadfactory);
Thanks user381878 for asking the question, and Andreas for the answer.