Calling JMX connection from thread in Java?

602 views Asked by At

The plan: Create admin thread and one for user, each of them could call upon connection in main. How can I call upon connection from my thread? Or should I be doing this connection in different place so my threads could see it? It should be something like this: mbeanProxy.startBattle(500);. That is how I call method from main class, but it does not work in threads tho. Server is JMX that uses MBeans.

Client.java:

    public class Client {
public static final String HOST = "localhost";
public static final String PORT = "9119";
public static Scanner sc;

    public static void main(String[] args) throws IOException, MalformedObjectNameException {
        sc = new Scanner(System.in);
        Map<String, String[]> env = new HashMap<>();
        System.out.println("Login: ");
        String login = sc.nextLine();
        System.out.println("Password: ");
        String password = sc.nextLine();
        String[] credentials = {login, password};
        env.put(JMXConnector.CREDENTIALS, credentials);
        JMXServiceURL url =
            new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanName = new ObjectName("serveris:type=Serveris");
        ServerisMBean mbeanProxy =
            (ServerisMBean) MBeanServerInvocationHandler.newProxyInstance(
                mbeanServerConnection, mbeanName, ServerisMBean.class, true);

        System.out.print( mbeanProxy.toString());
        Object dummyObject = new Object();
        Runnable task = new PlayerThread("test", dummyObject);
        Thread worker = new Thread(task);
        worker.start();
        mbeanProxy.startBattle(500);
        jmxConnector.close();
    }

}

ServerisMBean.java

package client;
public interface ServerisMBean {
    public void startBattle(int token);
    public void stopBattle();
    public int getToken();
}

And if someone notices any mistakes that I am making in my coding style please tell me, just a newbie and want to receive information on how I could become better at Java.

1

There are 1 answers

0
Nectos On BEST ANSWER

All I had to do is to take "mbeanProxy" and send it to thread by this way:

In main: Runnable task = new PlayerThread("test", dummyObject, mbeanProxy);

In thread: You have to name it at top of code, private final ServerisMBean mbeanProxy;

Then in constructor at same thread: public PlayerThread(String vardas, Object dummyObject, ServerisMBean mbeanProxy1){ this.mbeanProxy = mbeanProxy1; }

And I can call it inside thread by:

public void run() {
        System.out.println("test:"+mbeanProxy.getToken());}