Some quick tips to speed up Java and lower it’s memory usage

Java is an excellent programming language but too often the JVM seems to slow it down. Yes I know that there have been tremendous speed improvements in recent versions but the fact remains that it can still feel slow. It also tends to use an insane amount of memory to do just about anything (the heap is cheap is the name of the game!). Well thankfully there are ways you can tighten the JVM’s belt and even fine tune its garbage collection process.

Tune for Performance

Tuning the JVM for performance can be as easy as launching your Java application with a few simple command line options tacked on. For instance you can simply specify that you want to use the server JVM (included in the JDK) instead of the client one. The server JVM is tuned to take slightly longer to start but to run faster in the long run. You can enable the server JVM by passing the -server option. You can also tell the JVM to be more aggressive with its optimizations by adding the option -XX:+AggressiveOpts. Or tell the JVM to cache commonly used strings by passing -XX:+StringCache as an option.

Tune for Memory

Tuning for memory can be just as easy. Here are some useful commands that you can throw at the JVM to lower memory usage. You can set the starting heap size by using the command line option -Xmsn where n is the size. For instance -Xms2048k or -Xms2m (each 2MiB in size) are both valid. Alternatively to set the maximum heap size you can use -Xmxn where n is specified as above. This will force the JVM to attempt to keep the program within that heap size (by being far more aggressive with garbage collection). However this can be dangerous because your program will crash if it simply cannot fit within the maximum set size. Additionally you can also set the thread stack size by using -Xssn, again similar to above, but this might be even more dangerous than setting the overall program heap size. Finally you can enable a parallel garbage collector by using the command -XX:+UseParallelGC. This should hopefully speed up reference check searchings and the overall garbage collection rate.

Using the above methods you can really customize Java to run exactly as you wish on your machine. It might not be perfect, but with a little bit of work it can be a lot better than the defaults.