当我按照代码通过线程JMX connection
时,
private JMXConnector initConnection() throws Exception{
JMXServiceURL serviceURL = null;
try {
String URL = MessageFormat.format(connectorURL, new Object[]{hostName, port});
serviceURL = new JMXServiceURL(URL);
final Map<String, String[]> environment = new HashMap<String, String[]>();
environment.put(JMXConnector.CREDENTIALS, new String[]{userName, password});
return JMXConnectorFactory.connect(serviceURL, environment);
}
catch (Exception e)
{
throw e;
}
}
以下线程没有破坏,即使我关闭了连接并破坏了创建jmx连接的线程
GC守护进程,RMI RenewClean,RMI调度程序(0)这些线程在java JMX连接中没有破坏。
连接关闭的代码
public void closeConnection() {
if(jmxc != null){
try{
jmxc.close();
}
catch (IOException e) {
jmxc = null;
}
}
}
public void createMBeanServerConnection() throws Exception
{
try
{
jmxc = initConnection();
mbServerConnection = jmxc.getMBeanServerConnection();
}
catch (Exception e)
{
throw e;
}
}
这是完整的背景
public class Test1
{
public static void main(String[] args) throws Exception
{
Thread.sleep(120000);
Test t = new Test();
t.main(args);
Thread.sleep(120000);
}
}
public class Test
{
private String hostName = "";
private String port = "";
private String userName = "";
private String password = "";
private String connectorURL = "service:jmx:rmi:///jndi/rmi://{0}:{1}/jmxrmi";
private JMXConnector jmxc = null;
public static void main(String []args) throws Exception
{
Test t = new Test();
t.hostName = args[0];
System.out.println(args[1]);
t.port = args[1];
t.jmxc = t.initConnection();
MBeanServerConnection mbsc = t.jmxc.getMBeanServerConnection();
mbsc.queryMBeans(new ObjectName("*.*:*"), null);
t.closeConnection();
}
private JMXConnector initConnection()
{
JMXServiceURL serviceURL = null;
try
{
String URL = MessageFormat.format(connectorURL, new Object[]{hostName, port});
System.out.println(URL);
serviceURL = new JMXServiceURL(URL);
final Map<String, String[]> environment = new HashMap<String, String[]>();
environment.put(JMXConnector.CREDENTIALS, new String[]{userName, password});
System.out.println(serviceURL);
return JMXConnectorFactory.connect(serviceURL, environment);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public void closeConnection()
{
if(jmxc != null)
{
try
{
jmxc.close();
}
catch (IOException e) {
jmxc = null;
}
}
}
}
答案 0 :(得分:3)
您应完成任务,然后关闭连接。
public void createMBeanServerConnection() throws Exception
{
try
{
jmxc = initConnection();
mbServerConnection = jmxc.getMBeanServerConnection();
doYourThing();
}
catch (Exception e)
{
throw e;
} finally {
closeConnection();
}
}