Preserve Java stack trace across threads
You can use the Future<v>
object that returned from your submit invocation, then invoke the get()
method, if any exception occured during the task execution it will be re thrown.
Another option is to customize the default exception handler for the thread factory that creates the threads for your ExecutorService
. See for more details: Thread.UncaughtExceptionHandler
Following my comment, this is actually what I had in mind. Mind you, I don't have a way to test it at the moment.
What you pass from your parent thread is New Exception().getStackTrace()
. Or better yet, as @Radiodef commented, Thread.currentThread().getStackTrace()
. So it's basically a StackTraceElement[]
array.
Now, you can have something like:
public class CrossThreadException extends Exception {
public CrossThreadException( Throwable cause, StackTraceElement[] originalStackTrace ) {
// No message, given cause, no supression, stack trace writable
super( null, cause, false, true );
setStackTrace( originalStackTrace );
}
}
Now in your catch clause you can do something like:
catch ( Throwable cause ) {
LOG( "This happened", new CrossThreadException( cause, originalStackTrace ) );
}
Which will give you a boundary between the two stack traces.