Java/Scala/Kotlin: How to get the name of the current thread

When you’re working with multi-threaded programming in Java/Scala/Kotlin — such as when working with Thread, Runnable, SwingUtilities.invokeLater, Akka, futures, or Observable in RxJava — you may need to get the name of the current thread as a way to debug your code.

This example shows how to get the name of the current thread in Java:

Thread.currentThread.getName();

When you’re writing a simple, single-thread program the current thread shows up as “main.” In some RxJava code I worked with recently another thread showed up with the name “RxCachedThreadScheduler-1.”

If you’re familiar with Scala and Kotlin, you can easily convert that code to those languages.

In summary, if you need to get the name of the current thread in Java, Scala, or other JVM languages, I hope that’s helpful.