title: How to set JMX remote port system environment parameters through java code for remote monitoring?
body: <p>I have a program which requires dynamically (i.e. at run time) opening an available socket and start a JMX agent on it. This JMX parameters are being set inside the Java code and not through command line. This works fine. Thereafter it is needed to monitor( i.e issue JMX commands etc) through Java Visual VM
  remotely</p>
  
  <p>The RMI server agent in the program is on the lines of out of box management described at:
  <a href="http://download.oracle.com/javase/6/docs/technotes/guides/management/agent.html" rel="noreferrer">http://download.oracle.com/javase/6/docs/technotes/guides/management/agent.html</a></p>
  
  <p>The question I have can be summarized as:
  How can such command line properties be set to the system level 
  through the Java code, so that remote profiling can be used??</p>
  
  <pre><code>-Dcom.sun.management.jmxremote.port=1234
  </code></pre>
  
  <p>If the "jmxremote.port" and other parameters are set through command line,
  remote monitoring works fine. I am trying to find a way to do this through Java 
  and not through the command line.</p>
  
  <p>The program can not specify the port through the command line as the new available port has to be figured out at run time.</p>
  
  <p>The process needs remote monitoring and it works fine locally. 
  If the following parameters are not specified at command line, Java Visual VM does not connect to the process. </p>
  
  <pre><code>-Dcom.sun.management.jmxremote.port=1234
  -Dcom.sun.management.jmxremote.authenticate=false
  -Dcom.sun.management.jmxremote.ssl=false
  -Djava.rmi.server.hostname=10.0.0.128
  </code></pre>
  
  <p>I have tried.  </p>
  
  <pre><code>System.setProperty("com.sun.management.jmxremote.port",Integer.toString(port));
  </code></pre>
  
  <p>This is one of the first things done in the program before starting the JMXConnectorServer. Unfortunately it is not recognized. Only the run time properties (i.e. specified through command line are recognized for JMX connection by Java Visual VM).</p>
  
  <p>Also came across the way properties can be extracted from java collection classes but could not reach how to trace the property "com.sun.management.jmxremote.port="    </p>
  
  <pre><code>public static void setEnv(Map&lt;String, String&gt; newenv) throws Exception {
    Class[] classes = Collections.class.getDeclaredClasses();
    Map&lt;String, String&gt; env = System.getenv();
  
    for(Class cl : classes) {
  
      if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
  
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
  
        Object obj = field.get(env);
        Map&lt;String, String&gt; map = (Map&lt;String, String&gt;) obj;
  
        //map.clear();
        map.putAll(newenv);
      }
    }
  }
  </code></pre>
  
  <p>Any help would be appreciated! </p>