JMX初始化顺序

时间:2015-09-28 21:16:54

标签: java jmx

我现在学习JMX,但我无法理解为什么我的简单应用程序的工作方式。它对I"开始"的顺序很敏感。我的服务器类(只是println在无限循环中),我注册MBean。这是我的代码:

public interface SampleServerControllerMBean {
    public String getName();
    public void setName(String name);
    public void start();
    public void stop();
}

public class SampleServerController implements SampleServerControllerMBean {

    private SampleServer server;

    public SampleServerController(SampleServer server) {
        this.server = server;
    }

    @Override
    public String getName() {
        return server.getName();
    }

    @Override
    public void setName(String name) {
        server.setName(name);
    }

    @Override
    public void start() {
        server.start();
    }

    @Override
    public void stop() {
        server.stop();
    }
}

public class SampleServer {
    private String name = "";
    private boolean running = false;
    public SampleServer(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void start() {
        if(running) {
            System.err.println("Already running!");
            return;
        }
        running = true;
        while(running) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                running = false;
                return;
            }
            System.out.println(name);
        }
    }

    public void stop() {
        running = false;
    }

    public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
        SampleServer server = new SampleServer("Hello!");
        //server.start(); // case 2
        SampleServerController serverController = new SampleServerController(server);
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName("ru.aolisov.jmx:type=SampleServerController");
        mbs.registerMBean(serverController,name);

        server.start(); // case 1
    }
}

在这个例子中,这是行为: 1)案例1:注册MBean,然后start()。在JConsole中,我们可以看到MBean,一切正常。 2)案例2:start(),然后注册MBean。我们在JConsole中看不到MBean。

有人可以解释,为什么它对订单敏感?

P.S。 JDK 1.7.0.80,Windows 7.由Intellij Idea 14.1.4运行,由Debug,类SampleServer运行。

0 个答案:

没有答案