Why Java opens 3 ports when JMX is configured?

Using Oracle Java SE 1.8.0_121.

It's possible to set jmxremote.port and jmxremote.rmi.port to the same value, it's one less port opened. It's also possible to set jmxremote.host=127.0.0.1, to have that port (or those two ports, if you set them differently) bind to the loopback interface only.

Another port is still dynamically assigned though, and will bind to 0.0.0.0. I was not able to prevent this port with -XX+DisableAttachMechanism, and was also unable to make it bind to anything else than 0.0.0.0.


Contrary to common belief JMX/RMI doesn't need to open all these ports. You can actually force them to be same which will mean that at the end of the day you'll only need to punch one hole in the firewall (if firewall is your concern).

Try setting System Properties:

com.sun.management.jmxremote.port
com.sun.management.jmxremote.rmi.port

to the same value!!

Explicitly setting these will stop RMI from picking random ports. Setting them to the same value will make sure it opens less ports to listen on.

This will work in Java 7 update 25 or later.

What is the third port?

The third port that you see opened by your application (or the second if you followed my advice above) is used by the Java Attach API. It is what JConsole uses for connecting to "Local Process". The Java Attach API feature is enabled by default since Java 6 regardless of the com.sun.management.jmxremote property. This feature will use a random port (aka an OS ephemeral port) but it really doesn't matter because the feature only allows connections from the host itself. If you really dislike this feature then you can add -XX:+DisableAttachMechanism to the command line to disable the Java Attach API feature. Then you'll no longer see the java process (in this case Tomcat) listening on a random port.

How do I make JMX listen on the loopback interface only

With a custom made application you would use a RMIServerSocketFactory but this is Tomcat so you would have to do it using Tomcat's JMX Remote Lifecycle Listener.

On the other hand it doesn't matter now that you have the com.sun.management.jmxremote.local.only property since Java 7. It makes sure that only connections from the host itself are allowed. Mind you that JMX library doesn't achieve this by binding to loopback interface which would certainly be one way of doing it but also slight inaccurate as a host can potentially have several loopback interfaces.

In fact by and large (with the most recent additions to JDK wrt JMX) I would say that Tomcat's JMX Remote Lifecycle Listener is now redundant except if you want to bind to some really odd network interface.

Tags:

Java

Rmi

Jmx