Created
September 14, 2021 11:07
-
-
Save shai-almog/2b8078c8f60ecb09be3547f8f537df9f to your computer and use it in GitHub Desktop.
Convert the current stack to a checksum hex string which we can use in logs to identify call stack differences
This file contains hidden or 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
public class DebugUtil { | |
public static String stackHash() { | |
try { | |
// code from https://www.baeldung.com/java-stacktrace-to-string | |
StringWriter sw = new StringWriter(); | |
PrintWriter pw = new PrintWriter(sw); | |
new RuntimeException().printStackTrace(pw); | |
// checksuming for speed | |
int sum = 0; | |
for(char c : pw.toString().toCharArray()) { | |
sum += (int)c; | |
} | |
return Integer.toHexString(sum); | |
} catch(IOException err) { | |
return "Invalid Stack"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This simple function is useful for debugging code. Instead of doing
printStackTrace
and looking for minor differences in the logs we can use this function to make sure the calls are arriving from a well know stack. We can use this in conditional breakpoints to stop if the method is invoked from a different stack too.