Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Thread.getStackTrace() threadsafe?

A somewhat unorthodox situation - essentially I have thread A monitoring thread B. If thread A detects one of the periodic tasks thread B is responsible for (thread B is not part of a ThreadPoolExecutor, it is one of MINA's threads) has gone stale, thread A reports an error on it. So I am getting these errors and would like to know where thread B is jammed up on. So it seems smart for thread A to call thread B getStackTrace() and print the stack so I can see what silly activity B is jammed up on.

In practice I'm going to be comfortable doing this marginally, because if the task is not running chances are thread B's stack hasn't changed in quite some time because B is blocked. But in theory and sometimes in practice thread B's stack will be changing when thread A tries to get its stack trace. So I am wondering if this is a threadsafe operation.

like image 868
djechlin Avatar asked Mar 10 '26 08:03

djechlin


1 Answers

Looking at the source code of Thread it seems that getStackTrace() uses a private static native dumpThreads() method. The same method is used by Thread.getAllStackTraces() which is thread-safe according to its javadoc:

The threads may be executing while this method is called. The stack trace of each thread only represents a snapshot and each stack trace may be obtained at different time. A zero-length array will be returned in the map value if the virtual machine has no stack trace information about a thread.

like image 94
ShyJ Avatar answered Mar 12 '26 22:03

ShyJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!