Ok, you required to create MBean (managed bean that will be controlled by JMX) that will give you read access to 2 car parameters and you will be able to change max speed limit at runtime. To describe it, you need the next interface:
public interface ElectroCarMBean { public void setMaxSpeed(int maxSpeed); public int getMaxSpeed(); public int getCurrentSpeed(); }
Implementation will be very short and simple:
public class ElectroCar implements ElectroCarMBean { public int maxSpeed = 150; private Random rnd = new Random(); @Override public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } @Override public int getMaxSpeed() { return this.maxSpeed; } @Override public int getCurrentSpeed() { return rnd.nextInt(this.maxSpeed); } }
And after that you need to register you MBean (yeap, manually):
// Get the platform MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // managed bean instance ElectroCar car = new ElectroCar(); ObjectName carBean = null; // Uniquely identify the MBeans and register them with the platform MBeanServer carBean = new ObjectName("FOO:name=jmxsample.ElectroCar"); mbs.registerMBean(car, carBean);
After that, don't forget to add next parameters when you will be run your application:
-Dcom.sun.management.jmxremote \ -Dcom.sun.management.jmxremote.port=1617 \ -Dcom.sun.management.jmxremote.authenticate=false \ -Dcom.sun.management.jmxremote.ssl=false
It means run application w/ enabled JMX on port 1617, but without authentication (everyone can connect). So, your application is ready now! Run jconsole and check the result:
You can see that each attribute has a set of properties and the most important is read/write properties. If write property is 'true' you are able to set up new value from jconsole. Otherwise you could only read this value. In particular example, MaxSpeed can be change in runtime and it makes influence on max speed of the car. However, CurrentSpeed is readonly, and you can only perform monitoring (click 'Refresh' to update value)
As I said, MBean must be registered manually. So, it can be issue if you using some container for beans creation (like Spring). For example, Spring provide special bean MBeanExporter to give you possibility to MBeaning your classes, read more here