well actually
well actually

Reputation: 12370

Java Threads: Figure out which threads are still running

For debugging purposes, I want to figure out which threads of my program are still running. There's seems to be one or more threads that accidentally were not interrupted. Some sort of nice printable format would be a bonus.

Upvotes: 3

Views: 1507

Answers (5)

Matt
Matt

Reputation: 11805

"There's seems to be one or more threads that accidentally were not interrupted". I wound't say things weren't interrupted. Calling Thread.interrupt() doesn't force a runnable to stop. It sets the interrupt flag, and possibly causes blocking operations (like a Thread.sleep or java.nio calls) to throw either an InterruptedException or some other exception (like ClosedByInterruptException for nio). Your runnables have to check Thread.currentThread().isInterrupted() and behave nicely.

Upvotes: 0

Toby
Toby

Reputation: 9803

Following nogudnik's answer, tempus-fugit has a programmatic thread dump (and deadlock detection) feature, see http://tempusfugitlibrary.org/documentation/threading/dumps/

Upvotes: 1

nogudnik
nogudnik

Reputation: 247

If you're looking for a programmatic solution, something like this (in JDK 1.5 or later) should work:

Map<Thread, StackTraceElement[]> stack = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : stack.entrySet()) {
    System.out.println("Thread named '" + 
                       entry.getKey().getName() + 
                       "' is alive");
}

Upvotes: 3

Affe
Affe

Reputation: 47974

jVisualVM is your friend for this kind of debugging. It's in the /bin directory of your JDK install. Shows all of the threads as a graph view and allows you to drill down into what they're doing. The Thread Dump button will print out all of their current stack traces so you can see if something is stuck somewhere in your user code.

Upvotes: 3

Petro Semeniuk
Petro Semeniuk

Reputation: 7038

Use 'jps' command line tool to see active java processes and jstack for showing active threads.

jstack doc

example

Upvotes: 5

Related Questions