Search code examples
javamultithreadingstack-tracerunnable

Java - how to get the stack trace from before a Runnable?


I had a close look at the SO "questions that may already have your answer" here and surprised not to find what I'm asking for...

When an exception occurs in (for example) the EDT, or you just want to examine the stack for whatever reason, it's trivial to find the stack back to the run() of the Runnable. But how would you go about finding the thread (and hence stack) which ran the Runnable? and go about finding the thread (and hence stack) which ran that thread's Runnable... and so on and so on...

I'm aware of Thread.getAllStackTraces()... but how might one determine which of these threads called the "current thread"? Except "called" isn't the right word... I mean which ran the current thread.


Solution

  • When you have started your new thread, the original thread has moved on to doing other stuff. Getting the stack trace of what that thread is doing at a later point in time is probably irrelevant. What you want is to capture the stack as it is when a thread is started.

    What you could do is to create an Exception and pass to your Runnable when it is created. The exception will contain the stack up to when the runnable was created.

    Something like this:

    ExecutorService executor = Executors.newSingleThreadExecutor();
    
    public void foo() {
        final Exception starterStackTrace = new Exception();
        executor.execute(new Runnable () {
    
            @Override
            public void run() {
                try {
                    // do stuff
                } catch (Exception e) {
                    e.printStackTrace(); // Thread exception
                    starterStackTrace.printStackTrace(); // How thread was started
                }
            }
        });
    }