Custom thread pool naming is critical for debuggability.
Unfortunately, relying on default naming schemes often leads to situations where most of our threads are named in a cryptic manner:
Using core Java, there's no easy way to create custom ThreadFactory instances.
-
ThreadFactories.prefixed(String prefix)
-
ThreadFactories.prefixed(String prefix, ThreadFactory base)
-
ThreadFactories.suffixed(String suffix)
-
ThreadFactories.suffixed(String suffix, ThreadFactory base)
-
ThreadFactories.builder(String nameFormat)
withDaemonThreads(boolean daemon)
withUncaughtExceptionHandler(UncaughtExceptionHandler handler)
fromThreadFactory(ThreadFactory backingThreadFactory)
build()
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>thread-factory</artifactId>
<version>0.0.1</version>
</dependency>
compile 'com.pivovarit:thread-factory:0.0.1'
None - the library is implemented using core Java libraries.
0.0.1 (23-01-2019)
- Initial project version
That's reasonable. Just copy over the following code and use at will:
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* @author Grzegorz Piwowarek
*/
public class CustomThreadFactory implements ThreadFactory {
private String prefix;
private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
CustomThreadFactory(String prefix) {
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable task) {
Thread thread = defaultThreadFactory.newThread(task);
thread.setName(prefix + "-" + thread.getName());
return thread;
}
}