ddroboul
ddroboul

Reputation: 41

How to Obtain Thread Info/Statistics in Java

Title says it all. I have some code which is included below and I am wondering how I would go about obtaining the statistics/information related to the threads (i.e. how many different threads are running, names of the different threads). For consistency sake, image the code is run using 22 33 44 55 as command line arguments.

I am also wondering what the purpose of the try blocks are in this particular example. I understand what try blocks do in general, but specifically what do the try blocks do for the threads.

public class SimpleThreads {
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
long threadName = Thread.currentThread().getId();
System.out.format("id is %d: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
    String info[];
    MessageLoop(String x[]) {
        info = x;
    }
    public void run() {
        try {
            for (int i = 1; i < info.length; i++) {
                //Pause for 4 seconds
                Thread.sleep(4000);
                //Print a message
                threadMessage(info[i]);
            }
        } catch (InterruptedException e) {
            threadMessage("I wasn't done!");
        }
    }
}

public static void main(String args[])throws InterruptedException {
    //Delay, in milliseconds before we interrupt MessageLoop
    //thread (default one minute).
    long extent = 1000 * 60;//one minute
    String[] nargs =  {"33","ONE", "TWO"};
    if (args.length != 0) nargs = args;
    else System.out.println("assumed: java SimpleThreads 33 ONE TWO");
    try {
        extent = Long.parseLong(nargs[0]) * 1000;
    } catch (NumberFormatException e) {
        System.err.println("First Argument must be an integer.");
        System.exit(1);
    }
    threadMessage("Starting MessageLoop thread");
    long startTime = System.currentTimeMillis();
    Thread t = new Thread(new MessageLoop(nargs));
    t.start();

    threadMessage("Waiting for MessageLoop thread to finish");
    //loop until MessageLoop thread exits
    int seconds = 0;
    while (t.isAlive()) {
        threadMessage("Seconds:  " + seconds++);
        //Wait maximum of 1 second for MessageLoop thread to
        //finish.
        t.join(1000);
        if (((System.currentTimeMillis() - startTime) > extent) &&
                t.isAlive()) {
            threadMessage("Tired of waiting!");
            t.interrupt();
            //Shouldn't be long now -- wait indefinitely
            t.join();
        }

    }
    threadMessage("All done!");
    }
}

Upvotes: 3

Views: 3674

Answers (3)

invariant
invariant

Reputation: 8900

you can use VisualVM for threads monitoring. which is included in JDK 6 update 7 and later. You can find visualVm in JDK path/bin folder.

VisualVM presents data for local and remote applications in a tab specific for that application. Application tabs are displayed in the main window to the right of the Applications window. You can have multiple application tabs open at one time. Each application tab contains sub-tabs that display different types of information about the application.VisualVM displays real-time, high-level data on thread activity in the Threads tab.

enter image description here

Upvotes: 3

Udo Klimaschewski
Udo Klimaschewski

Reputation: 5315

If you are not able to use tools like VisualVM (which is very useful, IMHO), you can also dump the thread stack in Java, e.g. to your logfile. I am using such dumps on my server programs, when certain thresholds are crossed. I found doing such snapshots as part of the program very helpful. Gives you some hints on what happened before the system crashes and it is too late to use profilers (deadlock, OutOfMemory, slowdown etc.). Have a look here for the code: Trigger complete stack dump programmatically?

Upvotes: 0

Zhedar
Zhedar

Reputation: 3510

For the first issue: Consider using VisualVM to monitor those threads. Or just use your IDEs debugger(eclipse has such a function imo).

I am also wondering what the purpose of the try blocks are in this particular example.

InterruptedExceptions occur if Thread.interrupt() is called, while a thread was sleeping. Then the Thread.sleep() is interrupted and the Thread will jump into the catch-code.
In your example your thread sleeps for 4 seconds. If another thread invokes Thread.interrupt() on your sleeping one, it will then execute threadMessage("I wasn't done!");.
Well.. as you might have understood now, the catch-blocks handle the sleep()-method, not a exception thrown by a thread. It throws a checked exception which you are forced to catch.

Upvotes: 1

Related Questions