3

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!");
    }
}
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
ddroboul
  • 41
  • 1
  • 2

3 Answers3

3

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

invariant
  • 8,758
  • 9
  • 47
  • 61
  • it will print thread names too !,see my edited post for screen shot.Thread x,y are my thread names that i created :) – invariant Dec 16 '12 at 00:20
  • Right, I have found that page, but as you can see there are many other things listed there. In addition to the ones listed on your screenshot, I have ones called, Thread-1, Finalizer, Reference Handler, and main. So does this mean that my program from above only has 1 thread that is called 'Thread-1' or is 'main' also a thread therefore I have two threads? Thanks for your help – ddroboul Dec 16 '12 at 03:13
  • main is also Thread ,that every java application has, Thread -1 is thread that you created. – invariant Dec 16 '12 at 03:38
  • if you want to give some particular name to your thread , then change your line Thread t = new Thread(new MessageLoop(nargs)); to Thread t = new Thread(new MessageLoop(nargs),"My Thread Name "); – invariant Dec 16 '12 at 04:12
1

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.

Zhedar
  • 3,480
  • 1
  • 21
  • 44
  • thanks I tried VisualVM. Very cool tool. What is the difference between `Live Threads` and `Daemon Threads`? Also, how would I obtain the specific names of the threads using VisualVM, I don't see any names there – ddroboul Dec 15 '12 at 20:42
  • Daemon threads are non-user threads. If your program (the main thread ofc) has finished and a user thread would be running, the java vm wouldn't exit. If you use a daemon instead, this thread is stopped and the vm exits. Unfortunately I cannot help you with VisualVM, since I never used it personally. It still remains on my disk for some months :D – Zhedar Dec 15 '12 at 20:46
  • I just recognized it's already bundled in MacOS' JDK. I'm able to see the threadnames, if I right-click on the application(eclipse in my case), select "open" and navigate to "Threads". Both the "Timline" and the "Table" view have a column called "Thread"- This stands for the name of the thread imo. Does this answer your latest question? – Zhedar Dec 15 '12 at 22:00
0

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?

Community
  • 1
  • 1
Udo Klimaschewski
  • 5,150
  • 1
  • 28
  • 41