Showing posts with label JMX. Show all posts
Showing posts with label JMX. Show all posts

Wednesday, December 30, 2009

MBean Descriptors

JMX MBean/MXBean get accessed by different clients(Ex: JConsole, VisualVM, and etc.,), where it is our responsibility that to explain/descirbe the details of the Bean, it includes

  • MBean author, version and etc.,
  • Attribute display name, type, minValue, maxValue, defaultValue and recommendedValue and its behaviour
  • Operation display name, and its argument details

Java SE 6 has come up integrated way of annotation approach for all types of MBean, where we can specify the additional details, is called Descriptors.

Author.java
package com.example.mxbeans; 
 
import java.lang.annotation.Documented; 
import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 
import javax.management.DescriptorKey; 
 
@Documented 
@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Author { 
    @DescriptorKey("Author") 
    String value(); 
} 

HelloWorldMXBean.java

package com.example.mxbeans; 
 
@Author("Krishna")
public interface HelloWorldMXBean { 
    @DisplayName("GETTER: Name") 
    public QueueSample getName(); 
    @DisplayName("OPERATION: clearHelloCount") 
    public void clearCount(); 
} 

In runtime these metadata/annotation converts in to JAVA object, for most constructors in the classes MBean*Info (MBeanInfo, MBeanAttributeInfo, and so on), a parallel constructor exists with the same parameters plus an additional javax.management.Descriptor parameter. The same is true for OpenMBean*InfoSupport. The MBean*Info and OpenMBean*InfoSupport classes contain a getDescriptor() method.

Read: MBean Descriptors Tutorial

Resource Injection

Singleton Class

Singleton Class is created to maintain only one instance of this class object made available for application's ClassLoader. To achieve this, we have to add restrictions for this class access

  • All Constructors has to have private as access modifier
  • One factory pattern based, means atleast one public static method defined to create instance of this class
  • One static variable defined to hold this singleton object
  • Factory method has to be implemented gurantteing to not to create instance more than once.
    
    public static SingletonClass getInstance(){
    if(null == ins1)
    {
    ins1=new SingletonClass();
    }
    return ins1;
    }
  • To achieve thread safe, this getInstance() method has to use synchronized in method.

Singleton offers lots of advantage in creating instance in Application Context. In multi-threaded environment, if this synchronized getInstance() method called parallely then performance will be beaten heavily. Instance creation happens very early start up time of application, once object instanciated, then we have to avoid this if check and synchronized block execution. How to synchronized block in singleton class object instanciation ?

To answher the above question, we have to assign getInstance() result to the above mentioned static variable.

public static SingletonClass ins = getInstance();

However, this instance has to be initialized based on the argument passed then this could be painful job in creating instance and making it thread safe. Even we can build additional logic to achieve this, however, if an application comes with more number of singleton objects and Object lifecycle also be clearly maintained or controlled, then it is really more pain. We will end up spending time in this logic rather than in real business of application. Various tools available in market to provide application infrastructure runtimes. Eg: SpringSource

Java Enterprise Edition 5

Java EE 5 comes with Resource Injection concept, offers ease way of assigning object reference to the fields in a Class.

  • JSR 250 - Common annotations: Common Annotations for the Java Platform Specification, provides the semantics of the platform's common annotations.
  • JSR 220 - EJB beans: the Enterprise JavaBeans 3.0 Specification, Section 8.1, Annotation of Context Dependencies.
  • JSR 224 - Web services: the Java API for XML-Based Web Services (JAX-WS) 2.0 Specification, javax.xml.ws.WebServiceRef.
  • JSR 255 - JMX 2.0, Remote API for JMX, uses JSR 250 common annotations

public static DataSource catalogDS=null;
public synchronized javax.sql.DataSource getCatalogDS() {
try {
 if(null == catalogDS)
 {
  // Obtain the initial Java Naming and Directory Interface
  // (JNDI) context.
  InitialContext initCtx = new InitialContext();
  // Perform JNDI lookup to obtain the resource.
  catalogDS = (DataSource)
  initCtx.lookup("java:comp/env/jdbc/catalogDS");
  }
 } catch (NamingException ex) {
 // Handle failure.
 }
 return catalogDS;
}
 ...
public getProductsByCategory() {
    // Get the DataSource.
    DataSource catalogDS = getCatalogDS();
    // Get a connection and execute the query.
    Connection conn = catalogDS.getConnection();
    ...
}
In web.xml:
<resource-ref>
    <description>Catalog DataSource</description>
    <res-ref-name>jdbc/catalogDS</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

In the above code, getCatalogDS() will be called DAO design pattern methods to get a connection from DataSource. Establishing or making available this DataSource resource to the application mostly one time job in nature. But here in the above code, getCatalogDS() called everytime methods in DAO Class called.

In web Application, all possible resources are defined in web.xml with resource type. The same will be accessed from application like the way in sample code. Using resource injection, we can achieve this by placing annotation above the field


private @Resource DataSource catalogDS;

public getProductsByCategory() {
    // Get a connection and execute the query.
    Connection conn = catalogDS.getConnection();
    ...
}

No additional details required to be mentioned in web.xml. If we have multiple Datasource resource mentioned in web.xml, then we need to specify additional details in @Resource annotation.

Common annotations
  • @Resource
  • @Resources
  • @DeclaresRoles
  • @RunAs
  • @PostConstruct
  • @PreDestroy
EJB beans
  • @PersistenceContext
  • @PersistenceContexts
  • @PersistenceUnit
  • @PersistenceUnits
Web services
  • @WebServiceRef
  • @WebServicesRefs

Refer TechNote

JMX 2.0 API: MBeanRegistration

javax.management.MBeanRegistration interface allows user to perform pre or post MBeanServer registration or unregistration. We can achieve this by making resource injection. Right now, this available only for the class or subclass of MBeanServer, ObjectName, or SendNotification in JMX 2.0 API.


public Configuration implements ConfigurationMBean {
 @Resource
 private volatile MBeanServer mbeanServer;
 @Resource
 private volatile ObjectName objectName;
 ...
 void unregisterSelf() throws Exception {
  mbeanServer.unregisterMBean(objectName);
 }
 
 @Resource
 private volatile SendNotification sender;
 ...
 private void updated() {
  Notification n = new Notification(...);
  sender.sendNotification(n);
 }
 
 @Resource(type = MBeanServer.class)
 private volatile MBeanServerConnection mbsc;
 }

Note: A field to be injected must not be static. It is recommended that such fields be declared volatile.

Saturday, December 26, 2009

MBean vs MXBean

MBean vs MXBean

Manageable Resources are identified and instrumented as java objects, it could be Managed Bean(MBean) or advanced/extended/simplified Managed Bean(MXBean).

Managed Bean

MBeans can be any of java objects, in which we can store/retrive Serializable/Externalizable objects using methods. Based on the design pattern used in objects, we can differentiate either Standard(static) or Dynamic. Recommended to maintain Interface class name suffixed with MBean
Standard MBeans
Java objects that conform to certain design patterns derived from the JavaBeans component model.
  • fields are declared with access modifier as private, setter and getter methods with access modifier public, is called Attributes
  • Additionally, methods declared with access modifier public to do special operations, is called operations

public interface HelloWorldMBean {
//attributes
public String getName();
public void setName();

//operations
public void clearHelloCount();
public String sayHello(String name);
}
Dynamic MBeans
javax.management.DynamicMBean interface that offers more flexibility at runtime.
  • Object getAttribute(String attribute)
    Obtain the value of a specific attribute of the Dynamic MBean.
  • AttributeList getAttributes(String[] attributes)
    Get the values of several attributes of the Dynamic MBean.
  • MBeanInfo getMBeanInfo()
    Provides the exposed attributes and actions of the Dynamic MBean using an MBeanInfo object.
  • Object invoke(String actionName, Object[] params, String[] signature)
    Allows an action to be invoked on the Dynamic MBean.
  • void setAttribute(Attribute attribute)
    Set the value of a specific attribute of the Dynamic MBean.
  • AttributeList setAttributes(AttributeList attributes)
    Sets the values of several attributes of the Dynamic MBean.
Sample:
//Registering MBean in server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=HelloWorld");
Object mbean = new HelloWorld();
mbs.registerMBean(mbean, name);

//Retrieving MBean from server
HelloWorldMBean hwBean = JMX.newMBeanProxy(mbs, name, HelloWorldMBean.class);
hwBean.sayHello("JMX");

MXBean

MXBeans reference only a pre-defined set of types. Recommended to maintain Interface class name suffixed with MXBean. Implements interface of Dynamic or cusotmized JavaBean. Using MXBean, We can facilitate any client to use MBeans. Additional details required to use MXBean

  • In interface, Class name has to be suffixed with MXBean or annotation @MXBean has to be used.
  • In implementation class, annotation ConstructorProperties used to reconstruct the MXBean in retrievel time. Possible attribute names required to get from MBeanServer for this ObjectName has to be listed in constructor argument.
  • No Model-Class implementation not required to retrive pre-defined types.
  • CompositeData used to reconstruct Complex Objects.

However, in implementation class, annotation used to specify the attribute details in ConstructorProperties. And, In discovering and accessing code has the differences. Instead of directly retrieving the cusomer defined Bean, javax.management.openmbean.CompositeDataSupport has used to retrieve the data.



Sample:

public HelloWorld implements HelloWorldMXBean{
private String name;
@ConstructorProperties({"name"})
public HelloWorld(String name)
{this.name=name;
}
}

...

//Registering MXBean in server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=HelloWorld");
Object mbean = new HelloWorld();
mbs.registerMBean(mbean, name);

//Retrieving MXBean from server
//Predefined type retrieval
 String nameAttribute=mbs.getAttribute(name, "name");
 
//using CompositeData for complex java objects
CompositeData userdefinedBean = (CompositeData) mbs.getAttribute(name, "ComplexJavaObject");
String name = (String) hwBean.get("name");

//using proxy
HelloWorldMXBean proxy = JMX.newMXBeanProxy(mbs, name, HelloWorldMXBean.class);

Refer:
In java.net, What is an MXBean ? blog by Eamonn McManus.

Java Management Extensions (JMX)

Java Management Extensions (JMX)

Application is running for a long time suddenly started performing not good. We do not have any clue at this time. Idea started early 1998, there should be a way to interact the application from a local/remote vM to monitor and maintain the resource. For example, HeapSize almost reached maxSize and full collector not yet triggered, in this time we could make a request for GC from our application. This may not be the right solution, however, we can avoid OOM Exception.

In clustered environment, application may share the same configuration. User may update property in one node, which has to be replicated in other environment in flexible way. We cannot use tightly coupled model, since in failover scenario this will cause more pain to us. JMX Remote API, solves this problem by Change notification mechanism.

JSR details:

  • JSR 3 - Java Management Extensions
  • JSR 160 - JMX Remote API
  • JSR 255 - JMX 2.0


Typical 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.

The resources are instrumented as JAVA Object, known as Managed Beans(MBean). MBeans and its services sare registered in a Object Server, known as MBean Server or JMX agents. JMX Connectors helps agent to connect remote VM.

  • enables Java applications to be managed without heavy investment
  • provides a standard way to manage Java technology-based applications, systems, and networks
  • can be used for out-of-the-box management of the Java VM
  • provides a scalable, dynamic management architecture
  • leverages existing standard Java technologies
  • integrates easily with existing management solutions and emerging technologies. JMX solutions can use lookup and discovery services and protocols such as JiniTM network technology and the Service Location Protocol (SLP).

Examples TechNote

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com