I'm trying to set names to thread, but ExecutorService sets its own (like pool-1-thread-1). Question Naming threads and thread-pools of ExecutorService give the advice to use ThreadFactory. Ask you to consider this solution, is it safe enough?
public class Test {
private volatile String prName;
private volatile boolean prIsDaemon;
private final ExecutorService pool = Executors.newCachedThreadPool(
(Runnable r) -> {
final Thread t = new Thread( r, prName );
t.setDaemon( prIsDaemon );
return t;
}
);
public void Submit(boolean daemon, String name, Runnable run) {
prIsDaemon = daemon;
prName = name;
pool.submit( run );
}
public void Shutdown() {
pool.shutdown();
}
public static void main(String[] args) {
final Test test = new Test();
final Runnable r = () -> {
System.out.println( Thread.currentThread().getName() );
};
test.Submit( false, "aaa", r );
test.Submit( false, "bbb", r );
test.Shutdown();
}
}
RESULT:
aaa
bbb