A word about JMX--JMX Foundation

Source: Internet
Author: User
Tags exception handling int size memory usage readable sleep
What ?

The Java Management Extensions (JMX) API is a standard API for Management and monitoring of resources such as applications , devices, services, and the Java virtual machine.
Bottom line : The canonical API for managing system resources. where to use?

Ypical uses of the JMX technology include:consulting and changing application configuration accumulating statistics about Application behavior and making them available notifying of state changes and erroneous conditions.

One sentence typical application: change, view the program configuration, collect computational program behavior data, notification, alarm. Import Notion

An MBean was a managed Java object, similar to a JAVABEANTM, which follows the design patterns set forth in the INS Trumentation level of the JMX specification.
(4 kinds MBean)
-Standard MBeans
-Dynamic MBeans
-Open MBeans
-Model MBeans.

MBeans expose a management interface:a set of readable and/or writable attributes and a set of invokable operations, Alon G with a self-description. The management interface does not a change throughout the life of an MBean instance.

In a word, Mbean is the core of JMX, and Mbean is similar to JavaBean, where we obtain various information about the program detected by Mbean through an mbean-burst interface. Standard MBean

A standard MBean are defined by writing a Java interface called Somethingmbean and a Java class called Something that imple ments that interface.
A standard MBean are composed of the MBean interface which lists the methods for all exposed attributes and operations, and The class which implements this interface and provides the functionality of the instrumented resource.

In a word, standard MBean is an implementation of the interface: ***mbean implementation class (such as Timermbean, to see the API Docs), here to burst out the method of obtaining information, in order to activities you want to the various information.

Example:

/* Hellombean.java-mbean interface describing the management operations and attributes for T  He Hello World MBean. In this case there is operations, "SayHello" and "add", and the attributes, "Name" and "CacheSize".

*/Package Com.example.mbeans;
    Public interface Hellombean {//Operations public void SayHello ();

    public int Add (int x, int y);

    Attributes//A read-only attribute called Name of type String public string GetName ();
    A read-write attribute called CacheSize of type int public int getcachesize ();
public void setcachesize (int size); }
/* Hello.java-mbean implementation for the Hello world MBean. This class must implement all the Java methods declared in the Hellombean interface, with the appropriate behavior for  Each one.

*/Package Com.example.mbeans;
    public class Hello implements Hellombean {public void SayHello () {System.out.println ("Hello, World");
    } public int Add (int x, int y) {return x + y;  }/* Getter for the Name attribute.  The pattern shown here is Frequent:the Getter returns a private field representing the attribute value. In we case, the attribute value never changes, and for other attributes it might change as the application  Runs.  Consider an attribute representing statistics such as uptime or memory usage, for example.  Being read-only just means that it can ' t be changed through the management interface.
    */Public String GetName () {return this.name; }/* Getter for the CacheSize attribUte.  The pattern shown here is Frequent:the Getter returns a private field representing the attribute value, and  The setter changes that field.
    */public int getcachesize () {return this.cachesize;  }/* Setter for the CacheSize attribute. To avoid problems with stale values in multithreaded situations, it's a good idea for setters to be synchro  Nized.

    */Public synchronized void setcachesize (int size) {this.cachesize = size;
       /* In a real application, changing the attribute would typically has effects beyond just modifying the CacheSize  Field.  For example, resizing the cache might mean discarding entries or allocating new ones.  The logic for these effects would is here.
    */System.out.println ("Cache size Now" + this.cachesize);
    } private Final String name = "Reginald";
    private int cacheSize = Default_cache_size;
private static final int default_cache_size = 200;
 }
/* Main.java-main class for Hello World example.  Create the HelloWorld MBean, register it, then wait for forever (or until the program is interrupted).

*/Package Com.example.mbeans;
Import java.lang.management.*;

Import javax.management.*;  public class Main {/* For simplicity, we declare "throws Exception".  Real programs would usually want finer-grained exception handling.
    */public static void main (string[] args) throws Exception {//Get the Platform MBean Server attention!

    Mbeanserver mbs = Managementfactory.getplatformmbeanserver (); Construct the ObjectName for the MBean we'll register ObjectName name = new ObjectName ("Com.example.mbeans:type=h

    Ello ");

    Create The Hello world MBean Hello MBean = new Hello (); 
    Register the Hello World MBean attention!

    Mbs.registermbean (Mbean, name);
    Wait Forever System.out.println ("Waiting Forever ...");
    Thread.Sleep (Long.max_value);
 }
}

According to the JMX specification, a MBean interface consists of named and typed attributes that is readable and possib Ly writable, and named and typed operations that can is invoked by the applications that is managed by the MBean.

* * Sentence:
The interface is defined in **mbean, and this MBean interface has to specify the names of attributes (such as name, CacheSize), type, and burst out to get or set their methods as well as some operations. As an example, add () and SayHello ().
The core component of using a JMX agent to manage The MBEAN:JMX agent is the MBean server, which is registered before administration.

Mbeanserver mbs = Managementfactory.getplatformmbeanserver ();
Get the Mbean running on platform by calling the Java.lang.management.ManagementFactory.getPlatformMBeanServer () method Server. If platform does not, it will automatically get one (via Mbeanserverfactory.creatembeanserver ()). Send Message

MBeans can generate notifications, for example to signal a state change, a detected event, or a problem.

don't forget, Mbean can monitor an event, issue, status, and therefore send a message notification .

1. Implement Notificationbroadcastersupport or its sub-interface Notificationemitter.
2. Create a javax.management.Notification instance or its subclass (attributechangednotification) and pass it in Notificationbroadcastersupport.sendnotification.

 Package Com.example.mbeans;

Import javax.management.*;

Import Com.test.mbean.HelloMBean; public class Hello extends Notificationbroadcastersupport implements Hellombean {public void SayHello () {Sy
    Stem.out.println ("Hello, World");
    } public int Add (int x, int y) {return x + y;
    } public String GetName () {return this.name;
    } public int getcachesize () {return this.cachesize;
        } public synchronized void setcachesize (int size) {int oldsize = this.cachesize;

        this.cachesize = size;

        System.out.println ("Cache size Now" + this.cachesize); Notification n = new Attributechangenotification (this, sequencenumber++, System.currenttimemillis (), "Cachesiz

        E changed "," CacheSize "," int ", oldsize, this.cachesize);
    SendNotification (n);
            } @Override Public mbeannotificationinfo[] Getnotificationinfo () {string[] types = new string[] { AttributEchangenotification.attribute_change};
        String name = AttributeChangeNotification.class.getName ();
        String Description = "An attribute of this MBean have changed";
        Mbeannotificationinfo info = new Mbeannotificationinfo (types, name, description);
    return new mbeannotificationinfo[] {info};
    } private Final String name = "Reginald";
    private int cacheSize = Default_cache_size;

    private static final int default_cache_size = 200;
Private long sequencenumber = 1; }

The main note Hello.java the rest is similar to the previous example, slightly.
1. It inherits the Notificationbroadcastersupport (this class implements the Notificationemitter interface)
2. Instantiate a notification and pass the SendNotification (... ) Send
Smart farmer, try it yourself. MXBean

What?
is the enhanced version of Mbean, which is reinforced by defining a series of common types for us in advance.
How do I use?
First, define a **mxbean interface to implement. The implementation class is different from the standard MBean, and you can call it what you like.

Package Jmx_examples.MXBean.com.example.mxbeans;

Public interface Queuesamplermxbean {
    /** read-only attribute "queuesample" */public
    Queuesample Getqueuesample ();

    /** an operation "clearqueue" *
    /public void Clearqueue ();

is the same as defining a Standardmbean interface.

Package Com.example.mxbeans; 

Import java.util.Date; 
Import Java.util.Queue; 

public class Queuesampler implements Queuesamplermxbean { 

    private queue<string> Queue; 

    Public Queuesampler (queue<string> queue) { 
       this.queue = queue; 
    } 

    Public Queuesample getqueuesample () { 
        synchronized (queue) { 
            return new queuesample (new Date (), Queue.size (), Queue.peek ()); 
        } 
    } 

    public void Clearqueue () { 
        synchronized (queue) { 
            queue.clear () 
        } 
    } 

Implement the interface, there is nothing to say.

/** * Queuesample.java-java type representing a snapshot of a given queue.
 * It bundles together the instant time the snapshot was taken, the queue * size and the queue head.

*/Package Jmx_examples.MXBean.com.example.mxbeans;
Import java.beans.ConstructorProperties;

Import Java.util.Date;
    public class Queuesample {private final date date;
    private final int size;

    Private final String head; @ConstructorProperties ({"Date", "Size", "head"}) public queuesample (date date, int size, String head) {THIS.D
        ate = date;
        this.size = size;
    This.head = head;
    Public Date getDate () {return date;
    } public int GetSize () {return size;
    } public String GetHead () {return head; }
}

Note @constructorproperties ({"Date", "Size", "head"}), the runtime can find the corresponding get method according to the parameters. After this declaration, they represent three of them have getxxx method.
In fact, because the Mxbean mode invokes all the Get methods of queuesample, it is used to convert an instance to a Compositedata, annotated with @constructorproperties ({"Date", "Size", "head"}) , you can refactor a queuesample instance again when needed. (In fact, I do not fully understand, master please add.) Oh

In fact, MXBean can be a complex (attribute) object, mapped to a Compositedatasupport class (so-called Open Types), String,int and other simple types do not count.

Of course, our queuesample itself is a complex type and can be put into this complex type.

public class Main {/* For simplicity, we declare "throws Exception".  Real programs would usually want finer-grained exception handling. */public static void main (string[] args) throws Exception {//Get the Platform MBean Server mbeanser

        Ver mbs = Managementfactory.getplatformmbeanserver (); Construct the ObjectName for the MBean we'll register ObjectName name = new ObjectName ("COM.E

        Xample.mxbeans:type=queuesampler ");
        Create the queue Sampler MXBean queue<string> queue = new arrayblockingqueue<string> (10);
        Queue.add ("Request-1");
        Queue.add ("Request-2");
        Queue.add ("Request-3");

        Queuesampler Mxbean = new Queuesampler (queue);

        Register the Queue Sampler MXBean Mbs.registermbean (MXBean, name);
        Wait Forever System.out.println ("Waiting ...");
    Thread.Sleep (Long.max_value); }
}

If you don't have to **mxbean the result, instead of changing the example to Queuesamplermbean, then:

Because it would not is in its class path. This is because the complex Type property of the MBean cannot be loaded into classpath, and when you try to get its properties attribute, the ClassNotFoundException is reported. That is, only mxbean this mode, The complex type can be converted to a finer type (that is, OpenType).

If you want to dynamically get a mxbean for a JMX client, then do this:

1. Direct Access

Generically, using the following code.
CODE EXAMPLE 2-9 Accessing an MXBean directly

mbeanserver mbs = whatever ...; 
ObjectName name = new ObjectName ("Com.example.mxbeans:type=queuesampler"); 
Compositedata queuesample = (compositedata) mbs.getattribute (name,  
                             "Queuesample"); 
int size = (Integer) queuesample.get ("size");

2. Get through the agent

Mbeanserver MBS = whatever ...; 
ObjectName name = new ObjectName ("Com.example.mxbeans:type=queuesampler"); 
Queuesamplermxbean proxy = Jmx.newmxbeanproxy (MBS, name,  
                                              queuesamplermxbean.class); 
Queuesample queuesample = Proxy.getqueuesample (); 

An mbean also has a proxy, obtained through jmx.newmbeanproxy, similar to Newmxbeanproxy, try it yourself. MBean Descriptors

What?
is used to describe an Mbean description information, descriptors gives you a convenient way to add some metadata to your mbeans.
Others have nothing to say, their next example, see for yourself.

Reference:

http://docs.oracle.com/javase/6/docs/technotes/guides/jmx/tutorial/essential.html#wp1055648

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.