Renato Dinhani
Renato Dinhani

Reputation: 36696

In Java, it's possible discover what was the current method/methods executed?

I'm working with threads but after a time, most of them stop doing their job. The first thing I thought was a deadlock, but all are with state RUNNING.

I suppose there is an error in my logic or a new characteristic that I not realized and I must handle (it's a webcrawler).

Is it possible to get the current executing method or operation? I want this to see where my threads are trapped.

EDIT: I think that is something I need to handle or there is error in my logic because this happens after a time executing, not imeddiatly after the start.

Upvotes: 2

Views: 258

Answers (7)

jjnguy
jjnguy

Reputation: 138884

You can get the current stack trace in Java. You will get an array of StackTraceElement elements.

The first item in the array is the currently executing method.

See the following question for how to get the stack trace:

Get current stack trace in Java

Code might look like:

StackTraceElement[] trace = Thread.currentThread().getStackTrace();
StackTraceElement yourMethod = trace[1];
System.out.println(yourMethod.getMethodName());

Upvotes: 2

sjlee
sjlee

Reputation: 7866

Thread dumps are the right solution for the problem. If you want to do it programmatically within the process (some kind of monitoring logic), then java.lang.management.ThreadMXBean provides access to all threads along with their current stacks at the time.

Upvotes: 1

karmakaze
karmakaze

Reputation: 36154

Do you suppose your web crawler program is in a loop processing the same urls. Add some high level logging so each thread writes what it's processing.

Upvotes: 0

Vladimir Dyuzhev
Vladimir Dyuzhev

Reputation: 18336

Make VM to dump the threads (Ctrl-Break). Find your threads in the list. Look at the topmost stacktrace method. Done.

Upvotes: 2

acm0x
acm0x

Reputation: 775

You have 2 options:

  1. Use debug to get some understanding that was executed and what not.

  2. Use a lot of logmessages (you can also produce stacktraces in that messages)

Upvotes: 1

Borealid
Borealid

Reputation: 98479

A debugger is the way to go. This is what they are designed for.

Java debuggers with threading support are built into both the Eclipse and Netbeans IDEs.

Upvotes: 2

Esko
Esko

Reputation: 29377

It is, throw an exception, catch it immediately and save the stack. This is about as performant as asking an elephant to fly overseas but it's possible since it sort of extracts the current call stack to something you can work with.

However, are you sure you haven't run into a livelock?

Upvotes: 0

Related Questions