JVM Tuning

High CPU Utilization Finding Cause?

Hi All,

Jay SenSharma

Jay SenSharma

High CPU utilization is a very very common thing for an Application Server Administrator. Almost every week or quarter or may be every day we can see some High CPU utilization by the Application Server. It is very important for an Administrator or System Admin or a Application Server Support Person to find out what is causing the High CPU.

.
High CPU may cause System Crash or Server Crash or Slow Responsiveness of Server. So we need to find out which Thread is actually consuming more CPU cycles this will help us to find out whether the Thread is processing some application code ….there may be a code bug or it may be Application Framework bug as well…etc

.
So here we are going to see a very simple demonstration of generating High CPU and then we will see How to Analyze High CPU utilization. For this purpose we are going to use 2 very basic utilities

.
1). jps: to know How to use JPS utility please refer to : http://middlewaremagic.com/weblogic/?p=2291
2). top: This is an Operating System Utility .. Please refer to “man” (Manual of your OS like Linux/Solaris)
3). jstack: to know how to use jstack please refer to : http://middlewaremagic.com/weblogic/?p=2281

Generating High CPU

Step1). Create a Simple Web Application with the following JSP code:
“HighCpuGenerator.jsp”


<%
for (int i=0; i < 3; i++)
    {
       Thread x=new Thread(new Runnable(){

                  public void run()
                    {
                       System.out.println("Thread " +Thread.currentThread().getName() + " started");
                       double val=10;
                       for (;;)
                         {
                            Math.atan(Math.sqrt(Math.pow(val, 10)));
                         }
                     }
              });
 
        x.start();
    }
%>

<h3>High CPU generation ....Please collect the 4-5 times "Top" command Output and the 4-5 ThreadDumps.</h3>

Step2). Now Deploy your Application which is having this JSP.
Step3). Hit the Application using “http://localhost:7001/HighCpuWebApp/HighCpuGenerator.jsp

Analyzing High CPU:

Step4). Open a shell prompt and then get the Servers Process ID using “jps” utility which comes with Jdk1.5 and Higher inside the bin directory.

[jsenshar@jsenshar ~]$ export PATH=/home/jsenshar/MyJdks/jdk1.6.0_21/bin:$PATH
[jsenshar@jsenshar ~]$ jps -v

HighCpu_Collect5ing Process ID using JPS

HighCpu_Collect5ing Process ID using JPS

Step5). Now In the same command prompt run the “JStack” utility to collect some Thread Dumps in a File… Suppose if the Application Servers Process ID is “5398” which we got in previous step.

[jsenshar@jsenshar ~]$ jstack -l 5398 > ThreadDumps.log
[jsenshar@jsenshar ~]$ jstack -l 5398 >> ThreadDumps.log
[jsenshar@jsenshar ~]$ jstack -l 5398 >> ThreadDumps.log
[jsenshar@jsenshar ~]$ jstack -l 5398 >> ThreadDumps.log
[jsenshar@jsenshar ~]$ jstack -l 5398 >> ThreadDumps.log
HighCpu_ThreadDumps_JStack

HighCpu_ThreadDumps_JStack

Step6). Now In Parallel to collecting the Thread Dumps please collect the “top” commands output as well….like
(NOTE: Make sure that u collect the Thread Dumps and the Top commands results in Parallel whenever u observe any kind of High CPU utilization or Server Slow response)

[jsenshar@jsenshar HighCpu]$ top -H -b -p 5398

HighCPU_Top_Report

HighCPU_Top_Report

You will see some results like this :

top - 02:52:09 up 18:08,  4 users,  load average: 3.49, 3.25, 8.02
Tasks:  51 total,   6 running,  45 sleeping,   0 stopped,   0 zombie
Cpu(s): 96.6%us,  0.7%sy,  0.0%ni,  2.6%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Mem:   3848964k total,  3352224k used,   496740k free,    50940k buffers
Swap:  4194296k total,   400804k used,  3793492k free,  1116028k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 5522 jsenshar  20   0 2884m 412m  19m R 77.8 11.0  40:00.46 java
 5521 jsenshar  20   0 2884m 412m  19m R 66.9 11.0  39:57.34 java
 6900 jsenshar  20   0 2884m 412m  19m R 65.2 11.0   0:07.82 java
 5520 jsenshar  20   0 2884m 412m  19m R 54.2 11.0  39:57.70 java

Step7). Now U will observe that there are some Thread IDs which are consuming more CPU Cycles like Child Thread PID=5522 is consuming 77.8% of CPU similarly Child Thread PID 5521 is consuming 66.9 % of CPU Cycles. These are very Hign CPU utilization Threads inside the Main Parent Process ID 5398.

Step8). Now convert those PIDs into Hexadecimal values…..Example     the Hex Decimal Value for     5522 will be      1592. So now please open the Thread Dump and then find out the word 1592

Decimal Value of the Thread ID provided by OS

Decimal Value of the Thread ID provided by OS

Converted the Decimal Thread ID Value to Hexa Decimal Code

Converted the Decimal Thread ID Value to Hexa Decimal Code

"Thread-17" daemon prio=10 tid=0x00007fe824439800 nid=0x1592 runnable [0x00007fe7fa9e2000]
   java.lang.Thread.State: RUNNABLE
        at java.lang.StrictMath.atan(Native Method)
        at java.lang.Math.atan(Math.java:187)
        at jsp_servlet.__highcpugenerator$1.run(__highcpugenerator.java:83)
        at java.lang.Thread.run(Thread.java:619)

Here you will see that The Thread with id=0x1592 is actually causing the High CPU …Now u can tell your Developers to check the Stack Trace of this Thread so that they can correct their Application Code or If you see any API Code or Framework code there then you know what u need to do and where the problem is.

Like in above case u can see that  My JSPs code is actually causing High CPU    “at jsp_servlet.__highcpugenerator$1.run(__highcpugenerator.java:83)

.

.

Thanks

Jay SenSharma


Causes and First Aid of JVM Crash Issues?

Hi All,
Jay SenSharma

Jay SenSharma

Java Virtual Machine is a Native engine which allows our Java Applications to run. It performs the code optimization to improve the performance. In correct tuning, Low memory allocation, extensive code optimization, bad garbage collection strategy, API code leaking…etc are some of the reasons which may cause the JVM to crash.
.
Analyzing a JVM Crash is one of the very interesting and little time taking process sometimes it is even little complex to find out the root cause of the JVM Crash. Here in this article we will see some of the common mistakes, first aid solutions/debugging techniques to find out what kind of informations we can get by looking into the Core Dump.

What is Core Dump & Where to Find It?

Code dump is usually a Binary file which gets generated by the Operating System when JVM or any other process crashes. Sometimes it also happens that the JVM will not be able to generate the Crash dump. In Windows Operating Systems it will be generated in the Directore where the “Dr. Watson” tool is installed. In Windows it will be usually:  “C:Documents and SettingsAll UsersApplication DataMicrosoftDr Watson
.
By default in Unix based Operating Systems the Core Dump files are created in the directory where the Java Program/Server was started even sometimes it is generated in the “/tmp” directory of the Operating System. But using the following Java Option we can change it’s the Crash Dump/Heap   Dump generation locations:  -XX:HeapDumpPath=/opt/app/someLocaton/ and  -XX:+HeapDump JVM Options.
.
NOTE: These Flags does not gurantee that always the Heap/Crash dump will be generated at the time of JVM Crash. There are some more reasons behind the Core Dump not gets generated…like Process Limitations or the Less Disk Quota or unavailability of the Free File Descriptors.

Who Generates the Crash/Core Dump?

JVM does not generate the Coe dump. Rather it is the Operating System which generates the Core Dump. Core Dump is a Binary file which may be several hundred Mega Bytes or Giga Bytes in size. The Operating systems just log the exception/error messages and the details of the Threads along with the Native libraries loaded with that java process.
.
Many times a brief Textual Crash file is also generated by the JVM itself sometimes during Crash. Usually the file name is “hs_err_pid<WebLogicPID>.log” in case of Sun JDK. Similarly JRockit JVM also generates a Textual file with name “*.dump” in case of JVM Crash.

Use of -XX:+ShowMessageBoxOnError?

The Thread Dump is also very helpful to analyze the Server Crash. Thread dump tells us what was the status and activities performed by the Threads at the time of crash. It may be possible to get a thread dump before the process exits. HotSpot supports the JAVA_OPTIONS -XX:+ShowMessageBoxOnError
.
The corresponding JRockit JVM Option is -Djrockit.waitonerror.  When the JVM is crashing, it may prompt the user ” Do you want to debug the problem? ” This pauses the process, thereby creating an opportunity to generate a thread dump (a stack trace of every thread in the JVM), attach a debugger, or perform some other debugging activity.  However, this does not work in all cases (for eg., in case of stack overflow).
.
Along with above there are various options available to get the Thread Dumps as described in : http://middlewaremagic.com/weblogic/?p=823

What May Cause JVM Crash?

Reason-1). Usually Native Code causes the JVM Crash. Native code is a code written in Languages like C/C++, Java Native Interface APIs (JNI).
.
Reason-2). JDBC Drivers specially the Native Drivers.
.
Reason-3). JVM Code Optimization.
.
Reason-4). Less Memory availabity for Native Area of a Java Process.
.
Reason-5). Application Servers Native Performance Pack Libraries.
.
Reason-6). JVMs library itself can cause the Crash.
.
Reason-7). High CPU Utilization by the Threads. As described in : http://middlewaremagic.com/weblogic/?p=4348
.
Reason-8). Presence of Wrong Native Libraries in the PATH or in the “-Djava.library.path
.
Reason-9). Presence of A Different Version of Libraries in “java.library.path” or in “SHLIB” or in “LD_LIBRARY_PATH” variables. Like setting a 64-bit version of Library in a 32-bit version of JVM’s library path or vise-versa.
.
.

Tools To Analyze the Core Dumps?

Core/Crash dump is Operating System specific, So to analyze these Dumps we must use the Tools provided by the same Operating System vendors. Various kind of tools are provided by the Operating Systems to analyze these Core Dumps like:
Tool-1). Dr. Watson Tool  in Windows OS. Windows OS Start (Button)—>Run…—>drwtsn32
.
Tool-2). “pstack” and “pmap” in Solaris Operating System.
.
Tool-3). “procstack” and “procmap” in AIX Operating System.
.
Tool-4). “lsstack” and “pmap” in Linux Operating System.
.
Tool-5). “pflag” if available in HP-UX Operating System.
.
.

What May Help To Avoid JVM Crash?

It totally depends on What Caused the Crash or What Libraries caused the JVM crash to avoid the occurance of the JVM crash for next time. But following things should be taken in consideration while analyzing and avoiding the Crash.
.
Point-1). If the Native Jdbc Driver is causing issues, If our appliation is using the Native JDBC Drivers then Switching from Pure Native Jdbc Driver (Type-2 Drivers) to the Pure Java JDBC Driver (Type-4 Driver) may help.
.
Point-2). If the JVM Libraries are causing the Crash then Upgrading to a Later Version of the JDK. If that Application Server has that new JDK in it;s Supported Configuration list.
.
Point-3). If the JVM Code Optimization is causing the Crash, then Disabling the Code Optimization of JVM by applying the JVM Options.
For JRockit JVM Code Optimization can be disabled using JAVA_OPTION  -Xnoopt
For Sun JDK Code Optimization can be disabled using   JAVA_OPTION  -Xint
.
Point-4). Some times the “Just In Time Compiler” code generation also causes the JVM Crash. In these scenarios In Case of Sun JDKs disabling the JIT Compiler can help. We can disable the JIT Compiler by adding the JVM Option:  “-Djava.compiler=none
.
Point-5). Presence of a different bit version (32 bit or 64-bit libraries) of Library in the “-Djava.library.path
.
Point-6). Disabling the Application Servers Native Performance Packs. In WebLogic The Native IO Can be disabled using “-Dweblogic.NativeIOEnabled=false” JVM Option.
.
.
Thanks
Jay SenSharma

Basic JVM Tuning Tips

Hi All,
Jay SenSharma

Jay SenSharma

NOTE : Prerequisite of this post is that u are aware of the JVM Architecture and different generations of it…If not then Please refer to:  http://middlewaremagic.com/weblogic/?p=4464
And
.
Middleware performance is directly related to the JVM Tuning. Due to incorrect JVM Tuning we may face OutOfMemory, High CPU, StuckThread, Server Crash kind of issues. There is no standard value available for JVM Tuning which can be suggested so that a JVM can be called as 100% tuned because the JVM tuning totally depends on the Platform (Operating System), The Number of CPUs, The nature of Application (Like how many objects it creates? How Many Long Living Objects? How it implements Caching of Objects? …etc). But if we will keep following  things in mind while tuning the JVM then it may be really helpful.
.
Here are some very basic tips of tuning the JVM. Whatever Values of different JVM tuning parameters we are going to see and discuss in this Article is not an absolute value, it may vary according to your environmental setup and requirement.

Tip-1).  If Observed the GC time is Very Long.

If we observe that the Full Garbage Collection is taking a longer duration (Healthy JVM Usually takes around 2 to 2.5 Seconds for Full GC) then we must try following things:
.
Point-1). -Xincgc: Applying the “-Xincgc” JVM Option instructs the JVM to use the incremental Garbage Collection Strategy. Due to this option the Garbage Collector starts Garbage Collecting a fraction of heap at a time rather than Garbage Collecting the whole Heap space at once. So it reduces the long GC pauses.
.
Point-2). Apart from above we can even decide to decrease the Max Heap Size (If a very large heap is not required for us). Because if the Heap Size is very large then the Garbage Collector will take little longer duration to perform a full GC.
.
Point-3). Suppose if we dont have an option to decrease the Heap Memory then we can even think of adjusting the -XX:MaxNewSize (in JDK1.3 and JDK1.4) or  -Xmn (new name of Young Generation flag from JDK1.4 onwards). Increasing the -Xmn (Young Generation Area) helps in scenarios where the Application creates short living objects (less caching Applications). Because it inceases the time of minor GC, most of the application objects dies early.
.
Example-1:
Suppose the Maximum Heap is -Xmx1024m then we can choose the Young Generation EdenSpace as -Xmn340m… It means the 1/3 (one third of the Max Heap) Or in other way we can say that the Eden Space is One Third of the Maximum Heap.
Example-2:
It can also be achieved by setting the -XX:NewRatio. Because  -XX:NewRatio=2 means that 2:1 ratio of Tenured and Young Generation(Eden)

Tip-2).  Full GC Is Happening Very Frequently?

Many times some application calls System.gc() or Runtime.gc() to perform explicit Garbage Collection (Which is not recommended). Apart from this if an Application uses many Remote Method Invocation calls then in that case as well there are chances that the full GC may happen very frequently.  In this case we can try disabling the Explicit Garbage Collection statements using the JVM Option:  -XX:+DisableExplicitGC
Similarly If we dont require a very frequent RMI garbage collection then we can use the JVM Option:  –Dsun.rmi.dgc.client.gcInterval=1800000 ……     It means now the Explicit RMI Garbage collection will happen in 30 Minutes.

Tip-3).  OutOfMemoryError: unable to create new native thread?

If you see very frequently “java.lang.OutOfMemoryError: unable to create new native thread”. It usually happens if the -Xss Stack size is very large. Thread Stack size is a memory area where the Threads places their local variables and maintains the stack. Many applications which creates a lots of Threads which requires less memory for their local variables, still the JVM allocates a large memory StackSize for those threads…so after a certain number of thread creation JVM will not be allocate some more space for new Thread creation.
.
So it is recommended for these kind of environments that we decrease the StackSize because Sparc 32-bit JVM has -Xss512k as default value and 1024k Stack Size on Sparc 64-bit JVM. So if we want to create some more threads and if the Threads requires less memory stack then in that case we should try to decrease the StackSize.

Tip-4). How To Preserve Memory ?

We must disable loading some libraries in the memory of JVM if our application does not require them. Like if our Application does not require the JVMs Graphic Library then in that case we must diasble loading of Graphic libraries using the JVM Option  “-Djava.awt.headless=true”

Some More Tips….Keep Visiting Middleware Magic….
.
.
Thanks
Jay SenSharma

Copyright © 2010-2012 Middleware Magic. All rights reserved. |