Skip to content

Instantly share code, notes, and snippets.

@joshallenit
Created November 8, 2018 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshallenit/9f9271474d62d206174ae580147e876f to your computer and use it in GitHub Desktop.
Save joshallenit/9f9271474d62d206174ae580147e876f to your computer and use it in GitHub Desktop.
ThreadMonitor
import kotlin.math.min
/**
* Prints useful information about all threads in our process. Information includes
* [Thread.getName], [Thread.getState] and the stacktrace of the [Thread] up to 10 items.
*
* To stop thread call [interrupt].
*
* Things to look for:
*
* - Too many threads.
* - Rx IO threads that are not blocking on I/O (see their stack trace).
* - Computation threads that are not idle (see their stack trace).
* - Duplicate thread names because thread-pools are not being reused (for example more than one
* Glide or root OkHttpClient instance)
*/
class ThreadMonitor constructor(
// Default is to run every 2 minutes.
private val intervalMs: Long = 120000,
private val maxStack: Int = 10
) : Thread("ThreadMonitor") {
init {
// Use MAX_PRIORITY so that we can see what other threads are doing without waiting for
// them to go to idle.
priority = Thread.MAX_PRIORITY
}
override fun run() {
try {
while (!Thread.currentThread().isInterrupted) {
// Get all the threads and sort them by name
val threads = Thread.getAllStackTraces()
.toList()
.sortedBy { (thread, _) ->
thread.name
}
// For each thread, we get the index, name and stacktrace up to 10 items
// and log them
for (i in 0 until threads.size) {
val (thread, stacktrace) = threads[i]
val stack = stacktrace.toList().subList(0, min(maxStack, stacktrace.size))
System.out.println("Thread status %s %s (%s) > %s",
(i + 1), thread.name, thread.state, stack)
}
Thread.sleep(intervalMs)
}
} catch (interrupted: InterruptedException) {
System.out.println("Thread monitor was interrupted")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment