Guava tips: ThreadFactoryBuilder
Guava contains the simple and very useful class ThreadFactoryBuilder
, which is most commonly used to set the thread names when using an Executor
. This should always be done: thread names pop up in stack trace, when monitoring a running application with VisualVM, when printing deadlocks and so on. Doing this with ThreadFactoryBuilder
is very simple:
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("my-name-%d").build());
The threads in the pool will be named my-name-1
, my-name-2
and so on.
You can also have all the threads created as daemons by using setDaemon
. Finally, you can set an uncaught exception handler to handle in some way exceptions that the thread hasn’t caught, by using simply setUncaughtExceptionHandler
.
Let me stress it once more: please always set a name for your threads. It will make your life easier, and - with the help of ThreadFactoryBuilder
- it only takes one line of code.