我在调试时经常遇到问题。
有时线程结束时会抛出异常。
这个问题的原因是线程的调用者/启动者。
调用者发送不正确的参数或调用线程而不初始化某些东西。
为了找到调用特定线程的位置,需要付出一些额外的努力,因为堆栈跟踪是无用的。
如果我们可以将调用者线程的堆栈跟踪附加到被调用线程中会怎样。
考虑以下示例:
public class ThreadTest {
Thread t = new Thread("executeNonBlocking") {
@Override public void run() {
// What would be a good way to
// append callerStackTrace to the stack
// trace of this thread
System.out.println("inside");
new Throwable().printStackTrace();
}
};
public void executeNonBlocking() {
final StackTraceElement[] callerStackTrace = new Throwable().getStackTrace();
new Throwable().printStackTrace();
t.start();
}
public static void main(String[] args) {
new ThreadTest().executeNonBlocking();
}
}
输出
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
inside
java.lang.Throwable
at ThreadTest$1.run(ThreadTest.java:34)
期望的输出
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
inside
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
at ThreadTest$1.run(ThreadTest.java:34)
编辑:这是与@peter-lawrey 讨论后获得的解决方案
public class StackTraceInheritingThread {
private final Runnable r;
private volatile Thread th = null;
private String title;
private boolean daemon;
private InheritedStackTrace ist ;
private static final ThreadLocal<InheritedStackTrace> tl = new ThreadLocal<InheritedStackTrace>();
public StackTraceInheritingThread(Runnable r) {
this.r = r;
}
private final class StackTraceInheritingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override public void uncaughtException(Thread t, Throwable e) {
if(ist!=null){
e.addSuppressed(ist);
}
e.printStackTrace(System.err);
}
}
public StackTraceInheritingThread setName(String nm){
this.title = nm;
return this;
}
public StackTraceInheritingThread setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
public void start(){
if(th!=null){
throw new IllegalStateException("Already started");
}
th = new Thread(new Runnable() {
@Override public void run() {
tl.set(ist);
r.run();
}
},title);
th.setUncaughtExceptionHandler(new StackTraceInheritingUncaughtExceptionHandler());
if(daemon)th.setDaemon(true);
ist = new InheritedStackTrace();
th.start();
}
public static Throwable getInheritedStackTrace(){
return tl.get();
}
public static StackTraceInheritingThread make(Runnable r1){
return new StackTraceInheritingThread(r1);
}
private static final class InheritedStackTrace extends Exception {
}
public static void main(String[] args) {
StackTraceInheritingThread.make(new Runnable() {
@Override
public void run() {
System.out.println("heelo");
throw new RuntimeException();
}
}).setName("ExperimentalThread").start();
}
}