Skip to content

Instantly share code, notes, and snippets.

@jhalterman
Last active May 27, 2017 03:54
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 jhalterman/46f2eb13f1e220b3e06a169ccffc2d9a to your computer and use it in GitHub Desktop.
Save jhalterman/46f2eb13f1e220b3e06a169ccffc2d9a to your computer and use it in GitHub Desktop.
Experiments in thread aware exceptions
import java.util.Arrays;
public class ThreadAwareExceptionTest {
static class ThreadAwareThread extends Thread {
Throwable entryPoint;
ThreadAwareThread(Runnable runnable) {
super(runnable);
}
@Override
public synchronized void start() {
entryPoint = new AsyncInvocation();
super.start();
}
}
static class AsyncInvocation extends Exception {
AsyncInvocation() {
StackTraceElement[] stackTrace = getStackTrace();
// Remove ourselves from the stacktrace
setStackTrace(Arrays.copyOfRange(stackTrace, 1, stackTrace.length));
}
public static Throwable get() {
Thread t = Thread.currentThread();
return t instanceof ThreadAwareThread ? ((ThreadAwareThread) t).entryPoint : null;
}
}
public static void main(String... args) throws Throwable {
new Thread(() -> {
new IllegalStateException("Not thread aware").printStackTrace();
}).start();
new ThreadAwareThread(() -> {
new IllegalStateException("Thread aware", AsyncInvocation.get()).printStackTrace();
}).start();
Thread.sleep(10000000);
}
}
@jhalterman
Copy link
Author

jhalterman commented May 27, 2017

Outputs:

java.lang.IllegalStateException: Not thread aware
	at ThreadAwareExceptionTest.lambda$0(ThreadAwareExceptionTest.java:33)
	at java.lang.Thread.run(Thread.java:745)
java.lang.IllegalStateException: Thread aware
	at ThreadAwareExceptionTest.lambda$1(ThreadAwareExceptionTest.java:37)
	at java.lang.Thread.run(Thread.java:745)
Caused by: ThreadAwareExceptionTest$AsyncInvocation
	at ThreadAwareExceptionTest.main(ThreadAwareExceptionTest.java:38)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment