Tags down


Why does fetching results using "new Throwable().getStackTrace()[1].getMethodName()" termed as expensive?

By : 邵成磊
Date : September 15 2020, 02:00 AM
To fix the issue you can do You can get method name statically, without creating extra Throwable object
code :
   StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
} else {
   // Don't need JVM help for current thread
   return (new Exception()).getStackTrace();
public void methodB(){
        System.out.println("I am methodB");
                   .walk(frames -> frames.skip(1).findFirst())
                   .ifPresent(frame -> {
                        System.out.println("I was called by a method named: " + frame.getMethodName());

Share : facebook icon twitter icon

How Expensive is Thread.getStackTrace()?

By : Sinan Sislioglu
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Yes, there is some overhead to this call, but in all likelyhood, you're going to do something like this:
code :
public static boolean DEBUG_ON = true; //change this before your production build
public void debug(String message){
     //stack code here


How can a preallocated OutOfMemoryError truthfully implement Throwable.getStackTrace if thrown twice?

By : Amaldas
Date : March 29 2020, 07:55 AM
I wish this helpful for you The key to the answer lies in the contract to Throwable.getStackTrace():
code :
private static void test(OutOfMemoryError o) {
    try {
        for (int n = 1; true; n += n) {
            int[] foo = new int[n];
    } catch (OutOfMemoryError e) {
        System.out.println("Stack trace length=" + e.getStackTrace().length + 
                           ", object id=" + System.identityHashCode(e));
        if (e == o)
            System.out.println("Got the same OutOfMemoryError twice (abort)");

public static void main (String[] args) {
Stack trace length=2, object id=1743911840
Stack trace length=3, object id=2136955031
Stack trace length=4, object id=903470137
Stack trace length=5, object id=1607576787
Stack trace length=0, object id=2103957824 <--- new object cannot be allocated
Stack trace length=0, object id=2103957824 <--- same object reused
Got the same OutOfMemoryError twice (abort)

Getting different results for getStackTrace()[2].getMethodName()

By : Ramon
Date : March 29 2020, 07:55 AM
it should still fix some issue From Javadoc:

Why do I get different stacktraces with java.lang.Throwable#getStackTrace and java.lang.Thread#getStackTrace

By : Martine Hokker
Date : March 29 2020, 07:55 AM
like below fixes the issue As you've correctly noticed yourself, Thread.currentThread().getStackTrace() calls (new Exception()).getStackTrace(); This means that the stacktrace of the former will be exactly one frame longer.
If one method calls another, their stack traces cannot be the same by definition.

Throwable().getStackTrace()[0].getLineNumber() obfuscated by proguard

By : user1998799
Date : March 29 2020, 07:55 AM
wish helps you According to the manual, you need to do this:
code :
-renamesourcefileattribute SourceFile    
-keepattributes SourceFile,LineNumberTable
-keep class java.lang.StackElement
Related Posts Related Posts :
  • Mockito is not mocking the method
  • Sum of double values, strange result
  • How to integrate a spring boot application using spring cloud stream to IBM event streams on bluemix cloud
  • Counting number of days of a particular month when given a duration
  • JUnit test for void method ( output-input dependency )
  • Why does Collections.unmodifiableMap not check if the map passed is already an UnmodifiableMap?
  • ServiceLoader and services which are valid at all times
  • How to Run Cron Jobs in Kotlin Ktor?
  • How do I deserialize array of different types with GSON
  • Gradle Plugin dependency
  • java saying 'cannot find symbol' though method is declared in class
  • How to minimize the sum of the elements in the final array after performing k number of operation
  • Can I generate a jar with maven without method bodies in Java?
  • Java/Kotlin callback syntax - do I really need 2 callback definitions after conversion to Kotlin?
  • Spring boot RESTful - three tier architecture
  • What is a big double that I can use to simulate infinity?
  • Java Socket does not error but is not functional(?)
  • how can I get specific value of an array list using stream
  • I Can't Write A Triangle Pattern in Java
  • Unique Identifier for a video file in Android
  • How do I get a response to a http in java?
  • I don't know (Unresolved compilation problem:)
  • Custom ordering MSSQL hibernate Spring boot 2
  • How to build and run okhttp 3.10.0
  • ArrayList errors
  • How to create a partitioned table in BigQuery from java?
  • (JNI) Get Java method's memory address with GetMethodID
  • Java: Unable to understand for loop behaviour
  • Java - Rounding BigDecimal value with 2 decimal place at 2 levels
  • Minecraft-moding: Mod works only in IDE but not when exported as jar
  • Increasing Number Of Treads Cause The Longer Loop Duration
  • Using Java streams to find mode when there might be multiple modes?
  • How to access classes Vector of a Classloader in Java 12?
  • Java Regex: find single quoted text with escapes
  • How to Convert String of numbers to a distinct ArrayList
  • How to know if a date is in previous x minutes?
  • In Java, the expression "+ + + + + +" is executed, the compiler reports no errors and can execute correctly?
  • Long string concatenation problem in java?
  • How to get current week number and year in Java using GregorianCalendar?
  • What is the difference between ThreadContext.put() and MDC.Put()?
  • Mapstrut/Lombok: No property named "customfields" exists in source parameter(s) as on Dec 31 2019
  • Java:Add name of each instance of object to list
  • What is the more idiomatic use of super and extends in this case?
  • HttpConnect fails in android
  • How to add two Optional<Long> in java
  • While formatting a float number using System.out.format(), irrelevant answers are shown up. Why?
  • Operate a given Java stream pairwise
  • How do load a Service without using ServiceLoader.Provider class (for J1.8 compatibility)
  • Issues with creating gradle project in IntelliJ
  • How to create file choosers similar to default windows boxes?
  • Your code did not execute within the time limits in Hackerrank
  • How Do You Login To An ASPX Website Using A Jsoup
  • My do while loop is stopping after one iteration. how do I keep it going?
  • How do I repeatedly check if the user is verified in the Firebase Authentication?
  • keeping an android service running for a long time
  • Liveness / Health probe for Java threaded application
  • I am not very beginner of coding in java, But I need some help in understanding the constructor in java
  • Maven Shade : include only specific artifacts and exclude all the rest
  • Why does the "this" keyword print exactly what toString() is printing?
  • Lower and Upper Bound for Java Wildcard Type
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk