[Java Tip] Simple Custom ThreadNamingFactory

Assign Custom Thread names is a good practice for debugging Java code as well as inferring Thread Dumps. To use custom name, we need to provide an implementation of ThreadFactory

There is a simpler technique using Guava

Executor executor = Executors.newFixedThreadPool(2, new ThreadFactoryBuilder().setNameFormat("Heart Beat Monitor-%d").build());
Executor executor1 = Executors.newFixedThreadPool(5, new ThreadFactoryBuilder().setNameFormat("File Watchers-%d").build());

The example shows the usage with Executors, it returns a ThreadFactory which names the thread as per the pattern. The %d is assigned a unique integer value each time a new thread is created.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.