java - getting stacktrace with context to thread -


i trying current stack-trace of thread in java. have explored following methods:

  1. one of easiest way of printing stack trace of current thread in java using dumpstack() method java.lang.thread class

  2. another way printing stack trace using printstacktrace() method of throwable class

is there other approach can current stack trace of thread in java more efficient?

below class have designed..

public class stacktraceexample  {  private static final logger logger = logger.getlogger(stringreplace.class.getname());  public static void main(string args[])  {  //calling method print stack trace further down  first(); }   public static void first() {  second();  }   private static void second()   {  third();  }    private static void third()  {  //if want print stack trace on console use dumpstack() method    system.err.println("stack trace of current thread using dumpstack() method");   thread.currentthread().dumpstack();     //this way print stack trace current method     system.err.println("printing stack trace using printstacktrace() method of throwable ");    new throwable().printstacktrace();    //if want stack trace stacktraceelement in program    //use getstacktrace() method of thread class    stacktraceelement[] stacktrace = thread.currentthread().getstacktrace();    //once stacktraceelement can print console    system.err.println("displaying stack trace stacktraceelement in java");   for(stacktraceelement st : stacktrace)   {   // system.err.println(st);   }    }   } 

output :-

stack trace of current thread using dumpstack() method  java.lang.exception: stack trace  @ java.lang.thread.dumpstack(thread.java:1249)  @ test.stringreplace.third(stringreplace.java:38)  @ test.stringreplace.second(stringreplace.java:31)  @ test.stringreplace.first(stringreplace.java:27) @ test.stringreplace.main(stringreplace.java:23)   printing stack trace using printstacktrace() method of throwable  java.lang.throwable @ test.stringreplace.third(stringreplace.java:42)  @ test.stringreplace.second(stringreplace.java:31)  @ test.stringreplace.first(stringreplace.java:27)  @ test.stringreplace.main(stringreplace.java:23)   displaying stack trace stacktraceelement in java 

is there other approach can current stack trace of thread in java more efficient?

no. thread.printstacktrace() (or getstacktrace()) right way go. if current thread uses exception internally if thread generates stack trace directly.

one thing add if want stack trace of thread not sure use it, should more efficient save exception , call getstacktrace() when needed. stack trace not fleshed out in exception until call made. see code throwable.getourstacktrace() more details.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -