How to give command line option in java program?

423 Views Asked by At

I want to use Java flight recorder while running my java program. Can I pass arguments in java program itself and not while running the application.

For ex: I have a java class say "HelloWorld.class" I want to use java flight recorder while running this which i can achieve with

java -XX:+UnlockCommercialFeatures -XX:+FlightRecorder HelloWorld

But I want to achieve this unlocking commercial feature and start flight recorder from my java code. Is it possible?

1

There are 1 best solutions below

9
On

You should only do this if you have a commercial license from Oracle, and you should not put it into library code, so others by mistake unlocks it in production without their knowledge.

At runtime, it's probably easiest to do

Runtime.getRuntime().exec("jcmd " + pid + " VM.unlock_commercial_features");

In JDK 9 or later, you can get the pid from ProcessHandle;

ProcessHandle.current().pid() 

In earlier releases, you can get the pid from RuntimeMXBean:

String jvmName = ManagementFactory.getRuntimeMXBean().getName();
int index = jvmName.indexOf("@");
String pid = jvmName.substring(0, index);

Another alternative is to do it over JMX using DiagnosticCommandMXBean.

    ObjectName on = new ObjectName("com.sun.management:type=DiagnosticCommand"); 
    Object[] a = new Object[] {
        new String[] {
        }
    };
    String[] sig = new String[] {"[Ljava.lang.String;"};
    ManagementFactory.getPlatformMBeanServer().invoke(on, "vmUnlockCommercialFeatures", a, sig);