Last active
May 27, 2017 03:54
-
-
Save jhalterman/46f2eb13f1e220b3e06a169ccffc2d9a to your computer and use it in GitHub Desktop.
Experiments in thread aware exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Outputs: