How to read JVM parameters/arguments from within a running Java application

Java FAQ: How can I read/see Java Virtual Machine (JVM) command line arguments/parameters from within a running Java (or Scala) application.

For the last few days I’ve been working on a Java Swing application for Mac OS X systems, and bundling the application so it seems just like any other Mac app. (The app is actually written in Scala, but as you’ll see, the code is close enough to Java that it’s easy to understand.) In the process of doing this, I’ve been trying to set a lot of Java command line arguments, such as -Xms64m, -Xmx256m, -XX:+UseG1GC, and so on.

As I’ve been debugging the application I started wondering, “How do I know if these command line parameters are really being set?” I can see that they’re all in the app’s Info.plist file, but how do I know they’re actually being applied?

After digging around the internet for a while I was finally able to find this solution, which helps to show the JVM command line arguments:

// import what we need
import java.lang.management.ManagementFactory
import java.lang.management.RuntimeMXBean

// get a RuntimeMXBean reference
val runtimeMxBean = ManagementFactory.getRuntimeMXBean

// get the jvm's input arguments as a list of strings
val listOfArguments = runtimeMxBean.getInputArguments

// print the arguments using my logger
for (a <- listOfArguments) logger.log(s"ARG: $a")

I put this code in the main class of my Mac/Java application, bundle the app as usual, and then launch the application. After it starts running I see the following output in my log file:

ARG: -Djava.library.path=/Users/al/Projects/KillerApp/deploy/release/KillerApp.app/Contents/MacOS
ARG: -Xms64m
ARG: -Xmx256m
ARG: -XX:PermSize=32m
ARG: -XX:MaxPermSize=32m
ARG: -XX:+UseG1GC
ARG: -Dapple.laf.useScreenMenuBar=true
ARG: -Dcom.apple.macos.use-file-dialog-packages=true
ARG: -Dcom.apple.macos.useScreenMenuBar=true
ARG: -Dapple.awt.application.name=iTypewriter
ARG: -Dcom.apple.smallTabs=true

As you can see from that output, the RuntimeMXBean shows that all of my JVM command line parameters/arguments are recognized by the JVM. In this case that didn’t immediately help my debugging process, but it did let me know that the JVM parameters were not my problem.