9

I need to programmatically start a new java process and dynamically set the JMX port. So instead of doing this

-Djava.rmi.server.hostname=127.0.0.1 -Dcom.sun.management.jmxremote.port=9995 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false

I would like to do the following

System.setProperty("java.rmi.server.hostname", "127.0.0.1" );
System.setProperty("com.sun.management.jmxremote", "true" );
System.setProperty("com.sun.management.jmxremote.authenticate", "false" );
System.setProperty("com.sun.management.jmxremote.ssl", "false" );
System.setProperty("com.sun.management.jmxremote.port", "9995"  );

but it doesn't work. Any idea why?

Katerina A.
  • 1,268
  • 10
  • 24
  • IMHO its not possible. – SMA Dec 16 '14 at 15:47
  • 1
    See this [answer](http://stackoverflow.com/questions/7276881/how-to-set-jmx-remote-port-system-environment-parameters-through-java-code-for-r). You can still remotely monitor the JVM using [Java Attach API](http://docs.oracle.com/javase/7/docs/technotes/guides/attach/index.html) if that is your goal. – vsnyc Dec 16 '14 at 16:20
  • Can I have an accepted answer? – AutomatedMike May 23 '18 at 11:41

1 Answers1

19

By the time your code is called you've missed your chance to configure the jmxremote connector.

What you need to do is create your own rmi registry and a JMXConnectorServer to listen for rmi calls and pass them to the MBeanServer.

private void createJmxConnectorServer() throws IOException {
    LocateRegistry.createRegistry(1234);
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:1234/jmxrmi");
    JMXConnectorServer svr = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    svr.start();
}
AutomatedMike
  • 1,454
  • 13
  • 27
  • Thanks for this snippet. Works very well for me. – Matthias Wimmer Nov 04 '16 at 17:39
  • 1
    Great to know I've helped :) – AutomatedMike Nov 21 '16 at 09:44
  • careful, this will accept any password unless you do `HashMap env = new HashMap(); env.put("jmx.remote.x.password.file", "path-to-password-file");`, and pass that in when you create the `JMXConnectorServer`, where you currently have the `null`. Still, thanks so much for putting me on the right path!! – Mohamed Hafez Feb 09 '23 at 21:05
  • I've not been able to programmatically assign a JMX authenticator. Is there a way to inject it instead of using system properties? – Gray Feb 27 '23 at 18:34