Thursday, September 17, 2009

How to install jvmstat on linux

To install jvmstat on linux follow the below instructions;

1. Create a directory where you want to install jvmstat
2. Download jvmstat from http://developers.sun.com/dev/coolstuff/jvmstat/
3. Unzip the distribution to the directory you created in the first step.
4. Change your PATH settings as follows; PATH=$PATH:/path_to_your_unziped_distribution/bin
5. Set the environment variable: export JVMSTAT_JAVA_HOME=/your_jdk_installation_path
6. Create a policy file called jstatd.policy with the following entry:

       grant codebase "file:${java.home}/../lib/tools.jar" {
    permission java.security.AllPermission;
};


Thats about it. And your ready to use jvmstat. Just type "jps" and you will get a list of java applications running on your machine. Then just use that id and type "visualgc PID" to run visualgc which will give you an overview of memory allocations on the heap by your application.

More info on how to do remote monitoring can be found in the below link;

http://java.sun.com/performance/jvmstat/solaris.html

A nice Garbage collection monitoring tool

http://www.unixville.com/~moazam/stories/2004/05/18/visualizingGarbageCollection.html

jvmstat and visualgc is used to monitor application's Garbage collection. A very useful combination of tools to find memory leaks and the sort as I see it.

The JVM and how it handles stack and heap spaces

A recent discussion was going on about whether we should be using variables with a for loop or not. Going on those lines i stumbled upon a few articles explaining about the same.

http://rmathew.blogspot.com/2007/01/local-variables-in-java.html
http://www.coderanch.com/t/416620/Beginning-Java/java/What-stored-Stack-Heap
http://forums.sun.com/thread.jspa?messageID=2406140

A key point noted in the first post is
"The JVM specification that says that a JVM uses a fixed-size array for storing the values of local variables used in a method and each local variable maps to an index in this array. A Java compiler calculates the size of this array during the compilation of a method and declares it in the generated bytecode for the method."

So looking at that we can say that we do not necessarily need to worry about space allocation when thinking in terms of local variables as it is pre defined at compile time and is stored in a fixed-size array. Hence even if you create a String within a for loop, only one space allocated within that fixed-size array will be used. And according to the last forum post, the last comment sums it all up;

  • Class objects, including method code and static fields: heap.
  • Objects, including instance fields: heap.
  • Local variables and calls to methods: stack

  • But one thing to note is that in Java 6 some objects maybe created on the stack
    due to the "escape analysis" optimization used within Java 6. More info on that can be found at;

    http://java.sun.com/javase/6/webnotes/6u14.html