Friday, July 30, 2021

10 Examples of HotSpot JVM Options in Java

There are hundreds of JVM parameters or JVM Options exists inside sun JDK and its virtually impossible to keep track of every single JVM option and based on my experience we don't even use most of JVM flags except a couple of important JVM option related to java heap size, java options for printing garbage collection details and most likely JVM switches for setting up remote debugging in Java. but there are many other useful categories of JVM parameters that you at least like to be familiar with even if not intending to use them more frequently.

In this article, we will see examples of 10 different categories of JVM parameters that I found useful and use more frequently than others. I would recommend getting a full knowledge of what does a particular JVM option does by referring to the official list of JVM options.




JVM parameters in Java

On the basis of how we specify the JVM option it can be divided into two parts, JVM Options which starts with –X and those which starts with -XX:
1)    JVM Options that begin with -X are non-standard (they are not guaranteed to be supported on all JVM implementations) and are subject to change without notice in subsequent releases of the JDK.

2)    JVM Options or parameters that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice also.

Frequently used JVM parameters for heap, GC and debugging


I was thinking about writing a post on JVM options when I completed my post on Java Heap Size and Java Garbage Collection because these are two main areas where we see usages of various JVM flags. 

But it didn’t happen even after I covered the OutOfMemoryError post which has some JVM options to solve OutOfMemoryError in Java. Now I am happy that I have completed this piece of information and it's ready to be published. 

As always I look for your feedback, suggestions and any other JVM flags which I have missed and you guys find useful to share. 

Good knowledge of JVM options especially related to GC tuning is important for time-critical applications e.g. high volume low latency electronic trading platform where every microseconds matter. though getting the right combination requires a lot of profiling and trial and error and depends heavily on the nature of the trading application.




Important Points about JVM Options:

1)    Boolean JVM options can be  turned on with -XX:+ and can be turned off with -XX:-.

2)    Numeric JVM Options can be set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).

3)    String JVM options can be set by using -XX:=, and usually used to specify a file, a path, or a list of commands.



The command java -help lists the standard options (standard across different JVM implementations) for the Java application launcher. The command java -X can be used to see the Java application launcher's non-standard (X for extension specific to that JVM) arguments.

The -X options are non-standard and subject to change without notice. If you wish to detect which JVM arguments your currently running Java application is using, you can use the 

ManagementFactory.getRuntimeMXBean().getInputArguments()

Now here is my list of important JVM flags, switches, options or parameters which is most commonly used while running Java applications:


1) JVM memory options related to the java heap size

The following three JVM options are used to specify initial and max heap size and thread stack size while running Java programs.
-Xms        set initial Java heap size
 -Xmx        set maximum Java heap size
 -Xss>         set java thread stack size



2) JVM option to print gc details

-verbose:gc logs garbage collector runs and how long they're taking. I generally use this as my first tool to investigate if GC is a bottleneck for a given application.

-XX:+PrintGCDetails includes the data from -verbose:gc but also adds information about the size of the new generation and more accurate timings.

-XX:-PrintGCTimeStamps  Print timestamps at garbage collection.

You can further see these Java Performance and JVM internal courses on Udemy to learn more bout the performance tuning of Java applications. It's one of the advanced courses for Java programmers to learn more about Performance and Memory management including troubleshooting memory leaks in Java.





3. JVM parameters to specify Java Garbage collector

-XX:+UseParallelGC      Use parallel garbage collection for scavenges
-XX:-UseConcMarkSweepGC Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)
-XX:-UseSerialGC        Use serial garbage collection. (Introduced in 5.0.)

beware when you use GC Parameters if you are working on a time-critical application e.g. high-frequency trading application. GC is a time-consuming operation and it desired to create a balance.




4. JVM debug options JVM options for remote debugging

-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
to read more about remote debugging check How to Setup Java remote debugging in Eclipse and 10 Java debugging tips in Eclipse 



5. JVM options related to profiling

-Xprof
-Xrunhprof


6. JVM options related to java classpath

Xbootclasspath specifies classpath entries you want to be loaded without verification. The JVM verifies all classes it loads to ensure they don't try to dereference an object with an int, pop extra entries off the stack or push too many, and so on. 

This verification is part of the reason why the JVM is very stable, but it's also rather costly and responsible for a large part of startup delay. Putting classes on the bootclasspath skips this cost, but should only be used when you know the classes have been verified many times before. 

In JRuby, this reduced startup time by half or more for a simple script. The -Xbootclasspath option can be used to either prepend (/p) or append (/a) resources to the bootstrap classpath. You Can read more about Java Classpath in my articles How Classpath works in Java and How to Solve ClassNotFoundException in Java


7. JVM options to change  Perm Gen Size

These JVM options are quite useful to solve java.lang.OutOfMemoryError:Perm Gen Space.

-XX:PermSize and MaxPermSize
-XX:NewRatio=2  Ratio of new/old generation sizes.
-XX:MaxPermSize=64m     Size of the Permanent Generation.

8. JVM parameters to trace classloading and unloading

-XX:+TraceClassLoading and -XX:+TraceClassUnloading is two JVM options that we use to print logging information whenever classes load into JVM or unload from JVM. These JVM flags are extremely useful if you have any memory leak related to classloader and or suspecting that classes are not unloading or garbage collected.


9. JVM switches related to logging

-XX:+TraceClassLoading and -XX:+TraceClassUnloading print information class loads and unloads. Useful for investigating if you have a class leak or if old classes (like JITed Ruby methods in JRuby) are getting collected or not. You can read more about logging in to Java on my post 10 Tips while logging in Java

-XX:+PrintCompilation prints out the name of each Java method Hotspot decides to JIT compile. The list will usually show a bunch of core Java class methods initially and then turn to methods in your application. In JRuby, it eventually starts to show Ruby methods as well



10. JVM Switches for debugging purposes

-XX:HeapDumpPath=./java_pid.hprof  Path to directory or file name for heap dump.
-XX:-PrintConcurrentLocks       Print java.util.concurrent locks in the Ctrl-Break thread dump.
-XX:-PrintCommandLineFlags   Print flags that appeared on the command line.

That’s all on JVM Options, I understand it's not possible to remember all JVM flags but at least having an idea of what kind of JVM flags are available is a good asset. The image for JVM parameters is from Java tuning and Nutshell.  For full list of JVM options, you can refer to these links from the Oracle Java site: Java Hotspot VM Options


Other Java programming tutorials you may like
Why character array is better than String for storing password
How to convert String to Date in Java with Example
How to split String in java with Example

23 comments :

Anonymous said...

where are the logs located?? any specific folder?

Anonymous said...

Here is another very useful option I think every java programmer needs to know of:
-XX:+HeapDumpOnOutOfMemoryError

This will dump a hprof file on the moment
an outofmemory occurs. This hprof file
can than be debugged with eclipse memory
analyzer.

Sandeep said...

Very good points. Also all memory heap options are applicable to eclipse which can be configured in eclipse.ini file.
Extreme Java

Javin @ Generics in Java said...

@Anonymous, Thanks for "-XX:+HeapDumpOnOutOfMemoryError" , this is indeed an useful JVM option. Heap dump can help while diagnosing OutOfMemoryError in Java.

Javin @ Enum in Java said...

Thanks for your comments Sandeep. Indeed Memory adjustment in Eclipse is quite common because it ran out of Memory while working with large projects.

Anonymous said...

Nice JVM Parameters list, I have copied this list of JVM options and kept in my desk for quick reference. Thanks

Anonymous said...

There are some JVM options with -D also .What exactly is the differneces between -D vs -X vs -XX

Javin @ JDK vs JRE said...

Hi Anonymous, JVM options with -D are system property and you can access them by using System.getProperty("user.timezone"). you can pass any property value in format -Dproperty=value to JVM. -X and -XX are actual JVM options difference is that -XX are non statndard option and may not be supported on all JVM e.g. may supported in HotSpot JVM but may not be in IBM's JVM.

John said...

JVM options for memory can also include Setting up PermGen space. like -XX:PermSize for specifying size of PermGen and -XX:MaxPermSize for specifying maximum size of PermGen space. Also JVM options for tuning Young and Old Generatiosn like -Xmn , -XX:SurvivorRation and -XX:UseAdaptiveSizePolicy can be very useful. Anyway turning JVM for performance or memory is continuous task in Java development. let us know how these JVM options performs on your project.

Ryan said...

most important JVM option for memory and performance in 64 bit JVM is -XX:+UseCompressedOops, which reduces size of pointers used inside JVM to 32 bit in a 64 bit machine, enabling CPU to cache more data and improve performance. It also helps to reduce GC pauses significantly.

Anyul said...

is it possible for a web app to generate java.lang.OutOfMemoryError:Perm Gen Space by having to many system.out.println() outputs? I checked a heap dump generated on this kind of errors and found too many char[] arrays on my memory instanced.

Javin @ CyclicBarrier Example Java said...

Hi Anyul, that's is very unlikely of running out of Perm Gen, I would rather check for classloader leaks. You may wan to check this post on ClassLoader leak on Tomcat and causing PermgGen error

Unknown said...

So what is the stable standard jvm option?

Anonymous said...

Very good article....thanks!

Zim said...

Thanks Javin! I really had no idea about JVM parameters ever and I recently got a project requirement on Performance Tuning. Seriously, I wouldn't have ever known it was this easy if you wouldn't have written this article!! Thanks a ton! :D

Anonymous said...

Hi guys, What is the JVM command to print loading and unloading of class files into memory?

Admin said...

HeapDumpPath , JVM dumps the heap only in case of outofmemoryerror for debugging purpose am I correct ? This dump is used for the debugging purpose to find out the memory leak which has caused the out of memory exception.

Anonymous said...

I was asked -server , -client VM option in a recent interview. I have never used it but it seems it's used a lot in finance domain. It would be nice if you can include it.

Vikas Kukreti said...

I am New to this subject and willing to know that where to Implement these JVM commands and how ? will be glad if u can provide the Sample for this

Groundblue said...

The option "-XX:NewRatio=2" is for New/Old gen in Heap size not for "Perm Gen Size"

Ikem said...

> _they_ are not guaranteed to be supported on all JVM implementations

> -_Xss_ set java thread stack size

Typos.

kumar said...

Do we have any parameter to refresh JVM using HOTSPOT

javin paul said...

Hello Kumar, what do you mean by refresh JVM?

Post a Comment