JMX : Introduction and Hello World Application

Jmx : introduction and hello world application

– Basic Java knowledge
– Java version 6 and above.

1.As title says, It is very simple JMX Hello World to expose JMX to naive java programmers.
2. The term MBean, MBeans, Managed Bean, Managed Bean Server or MBeanServer has nothing to do with EJBs.
3. This tutorial doesn’t dig deep into theory of JMX and its architecture. Read it here

What is JMX ? Let’s take it from Web.

Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices (e. g. printers) and service oriented networks.

In short:
With java5 and above jvm provides a way to manage your application while it is running.All it needs to know is the resources that you want to manage.When these resources are managed via JMX they are called Managed Resources and represented as ManagedBean or MBean. Each jvm will have its own mbean server that will manage the resource defined as managed resources.

First this comes to mind is why not use profilers like jprofile, profilers give you control over runtime environment e.g. jvm level control, JMX gives you control of your application.

Lets take a small example:

We have a calculator service doing big calculations for the given input can calculation is cpu and memory intensive job. each request to calculator service runs in a seperate thread. We have a thread counter and thread max_count to keep count of thread running and maximum threads allowed.


Sometime, requests volume is high, so system will stop accepting requests after thread max_count is reached. however it may happen that calculations are less cpu/memory intensive and more jobs can be accepted/more threads can be created.

Solution Requirement :

We need a way to dynamically change the thread max_count at runtime based on the cpu usage and memory consumptions.

Solution :

JMX allows to do that runtime, without changing my code.

What we need is, to have some way to change max_thread_count at run time.
Lets create a simple interface with the following.

package com.example;

 * interface lists out the operations that we would like to get exposed at runtime.
 * @author sudhir mongia
public interface CalcServiceMBean {

 // set the new current max_thread_count
 public void setMaxThreadCount(int count);
 // get me current max_thread_count
 public int getMaxThreadCount();


Now time to see our Calculator Service which does the calculation and uses thread count to do its work.

package com.example;

 * CalcService this will simulate the behavior of calculator service.
 * This implements CalcServiceMBean,which also means the methods that we would like to expose.
 * @author sudhir mongia
public class CalcService implements CalcServiceMBean{

 //no of threads currently running
 private int threadCount;
 //Max no of threads this can have
 private int maxThreadCount = 10;

 * Method to accept calc jobs and run in seperate thread,
 * only if it in under limits.
 public boolean acceptJob() {

 if(threadCount< maxThreadCount) {

 System.out.println("Currently Running" + threadCount + "jobs");
 return true;
 // here goes the logic to create thread... and do the works.

 }else {
 ///too many thread running can't accept more jobs
 System.out.println("Too busy to accept new work.");
 return false;


public int getThreadCount() {
 return threadCount;
 //set the threadCount
 public void setThreadCount(int threadCount) {
 this.threadCount = threadCount;

 //get the max_thread_count
 public int getMaxThreadCount() {
 return maxThreadCount;
 //set the max_thread_count
 public void setMaxThreadCount(int maxThreadCount) {
 this.maxThreadCount = maxThreadCount;


Important things to notice in above code.:
1. Service name is CalcService and it implements the CalcServiceMBean. It is convention and requirement to have interface name ending with MBean and actual implementation name as prefix.
2. as always with interfaces, this class implements the methods of CalcServiceMBean.
3. It keeps on accepting jobs, within the limits of max_thread_count.

Lets have a Main class to run this piece of code.

package com.example;


public class Main {

 public static void main(String[] args)
 throws Exception {

//Lets get the current MBeanServer..
 MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
 ///in jmx, each MBean will have unique name
 ObjectName name = new ObjectName("com.example:type=CalcService");
 CalcService calcService = new CalcService();
 //register calcservice with Mbean server before doing any work.
 //this will give handle to jmx console to use the operations exposed by MBean
 mbs.registerMBean(calcService, name);

 for(int i = 0;i<100;i++) {
 // we know that it will give us busy message after 10 jobs as set in max_thread_count in CalcService
 //lets give some sleep after 15,
 //so that we can get time to go and change max_thread_count from jmx console
 // and then it will start accepting jobs.
 if(i>15) {


Lets run the Main class, the following output will appear on the console and program will be running.

Currently Running1jobs
Currently Running2jobs
Currently Running3jobs
Currently Running4jobs
Currently Running5jobs
Currently Running6jobs
Currently Running7jobs
Currently Running8jobs
Currently Running9jobs
Currently Running10jobs
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.

So it says, it can’t accept new jobs.. Lets keep this running here, go and manipulate the max_thread_count.
We can do it easily using jconsole.

simple run jconsole.

CMD> jconsole

You will see the screen shot like this, select our process com.example.Main as connect to it.

jconsole open

jconsole open

See MBean, section, you should see the MBean calcService .. like the following.

Lets change the count to 20(double click and change) and then to 25. and notice the output on console.

this will be following.

Currently Running1jobs
Currently Running2jobs
Currently Running3jobs
Currently Running4jobs
Currently Running5jobs
Currently Running6jobs
Currently Running7jobs
Currently Running8jobs
Currently Running9jobs
Currently Running10jobs
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Too busy to accept new work.
Currently Running11jobs
Currently Running12jobs
Currently Running13jobs
Currently Running14jobs
Currently Running15jobs
Currently Running16jobs
Currently Running17jobs
Currently Running18jobs
Currently Running19jobs
Currently Running20jobs
Too busy to accept new work.
Too busy to accept new work.
Currently Running21jobs
Currently Running22jobs
Currently Running23jobs
Currently Running24jobs
Currently Running25jobs
Too busy to accept new work.

So if you see the console output, it shows you that CalcService, stopped after 10 jobs initially and then to 20 and 25. It accepting jobs intermidiate after we modified the max_thread_count from jconsole using the MBean that we created.

Hope this gives a good intro to JMX and its capabilities.Feel free to write to me for questions comments.


Love And Java

Love And Java

This is just a small write-up on relating Java with Love.

We have equals method and == operator in java. So what is the difference between these two?

First, the == operator compares two object references to see whether they refer to the same instance.

Object obj1  = new MyObject(“Sudhir”);

Object obj2  = obj1;

We say obj1 == obj2 will be true as they are pointing to same instance. Calling equals method may or may not return true.

Second equals method compares the contents of two objects deep inside.

Object obj1  = new MyObject(“Sudhir”);

Object obj2 = new MyObject(“Sudhir”);

Now if we say obj1 == obj2, will be false as they point to different instances. But if we call obj1.equals(obj2) or obj2.equals(obj1) will true, because they are equal deep inside.

So how do we relate this with Love? For two people to be in love should be equal in the lines of equals method not on the lines of == operator.

Love on the lines of == operator : two people have similar reference for few things. Like common hobby, interests, attitudes, from same college/office/locality/culture. == operator implementation comes inbuilt, you don’t need to do anything for it, Similarly 2 people have same or different hobbies, thinking, views ,is something inbuilt.

Love on the lines of equals method: It’s deep inside. Both are equal, though they have different references but they are equal. They understand each other, respect each other, know each other very well and can decipher any action in any situation. Like for equals method to work correctly you need to write extra code and correct code (otherwise it will rely on == operator), and to be in deep love, you need to do extra things to understand him/her, devote and dedicate yourself and very important respect each other’s feeling/decisions.

Disclaimer: Views expressed here on love are completely mine and not subjected to any discussion or debate. It just a logical relation with love and java discussed here.

Learning Design Patterns – Template Method Pattern

I am writing this blog for people who are interested in learning design pattern and can use on the job. This blog series will discuss couple of design patterns which are basic and will give you a good start. The intention here is to discuss a design pattern and assimilate its usage in the Java and J2EE. Prior knowledge to Java and J2EE is must to understand the sample usage of the design patterns.

Design patterns are reusable solution to a particular problem that is expected to be reoccurring. Design patterns are there for long time. People are using in their application and have got good results. Design patterns are based on the underlying principles/best practices of writing code in a given programming language. However Design patterns are not tied to any programming language, these are generic solutions and can be implemented in any language.

How this blog is different? This blog will tell you the definition of the design pattern and will show you an example of the usage from Java or java based frameworks. If required will be showing you sample code as well.

Template Design Pattern or Template Method Pattern: The dictionary meaning for the word template is

“Something that serves as a model for others to copy: “a template for change” or “A model or standard for making comparisons”

A template makes it easy to derive our own version of a particular document/process that is what Template Design pattern is all about.

Definition: A template method defines the program skeleton of an algorithm. One or more of the algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed.


Template Method Pattern

Template Method Pattern with sample usage


Example Usage: The classic use of this method is in J2EE. Whenever we need to write a servlet we need to extend the HttpServlet and implement doXXX()  as per our need, rest will be taken care by the HttpServlet class. Service method in the HttpServlet will be called by container which will receive the request and then later doXXX()  will be called from our servlet.  Here service method is acting as template method.

So Template Method

–          Very Easy to use and start with.

–          Allows subclass to change certain behavior, still control remains with parent class.

Hope this will help… I’ll post for some more design patterns soon.

Learning Scala

I have started learning scala in these days with the intent of becoming a polyglot programmer. Initially, I started learning scala from the book “Learn Seven Languages in Seven Days”. After completing three days I realized that I am missing some important concepts and decided to read a full fledged book on Scala. I started with “Programming in Scala by Martin Odersky”, book is very good for a newbie like me who came from Java Background. The author has explained the language fundamentals by citing references and example from Java Language. I could spot few important points in first 3 chapters. I am writing here for someone who wants to start learning scala, this will give a quick start.

  • Scala stands for “scalable languages”. Scala is a blend of object-oriented and functional programming concepts.
  • SCALA is statically typed and it has type inference capability. A static type system classifies variables and expressions according to the kinds of values they hold and compute. At the same time, scala compiler doesn’t infer the types of parameters to a function/procedure.
  • Scala was designed for seamless interoperability with Java. Scala programs compile to JVM bytecodes. Their run-time performance is usually on par with Java programs. Scala code can call Java methods, access Java fields, inherit from Java classes, and implement Java interfaces
  • You can run scala code snippets directly on Scala interpreter on command prompt, there is no need to write a complete program.
  • Scala uses var and val for defining variable and constants. var for variables and val for constants. val is similar to final keyword in java. Scala has introduced the concept of mutable variables using val as mutable states limit concurrency.
  • Defining functions/procedures in scala

def <FuncName>(Argname1:argType,ArgName2:Argtype):returnType={..code inside function}

def sum(num1:Int,num2:Int):Int={return num1+num2}

  • Scala’s Unit type is similar to Java’s void type
  • In Scala array elements are accessed using () not with [].. e.g. args(0) in scala using parenthesis and args[0] in java using square brackets.

Knowledge Sharing – is it required?

Here I am specifically discussing the need of knowledge transfer to your replacement when you move to new assignment in the same organization or moving out of organization.

I have experienced month-long knowledge transfer session supported by KT Plan document.It takes lot of efforts to be part of knowledge sharing activity.

However in my recent assignment where we adopted Agile methodology for development, this was not the case.People joined the team, left the team but the KT activity was very limited. The concept of developer pairing and Daily standup were the reason behind this. Everyone was aware about whats going on, who is working on WHAT. That really helped us to achieve success. 

This experience gave me one more reason to support Agile Methodology for software development.


Andriod for Java Developers

Last week I spent some time exploring Android. To my surprise I was able to download sdk, configure and do Hello world application in less than 3 hours.

Google has made it so simple that anyone who has knowledge of java can do this example in such a short time. Developer guide is written so well with all scenarios that leaves to room for use mistakes.

It was the best experience with any platform/technology.

Java Web Application Development Kick off – Technical Items

Recently I got a chance to start development of a new application. During initial analysis I thought of having a list of constituents for development of a web application. I tried to look on the web for it but couldn’t gather much on it. Then I decided to prepare a list on my own. Once I finished preparing the list, I find it helping me too much in planning and project execution. Here in this blog I am sharing the list and hoping that this would help other as well. In this I have mentioned tools/api/software that can be used but no recommendation of anyone and there could be lots more for a task.

Requirement Description Few Sample Available API/Tool/Software options
Application Server Required for
– Application Deployment
– Could be different for dev and prod environment
– if required access LDAP,JNDI And connection pooling features can be used
Tomcat,Jboss, WebLogic, WebSphere….
Auditing Required for Audit requirement for the application.
– Action based auditing
– Transaction based auditing
Log4j or slf4j, ApacheCommonLogging.
Authentication Required to Authenticate a used entering into system LDAP, JAAS, Simple J2EE container based, Database/file storage or authentication information
Caching Required at different layers
– Application server level
– Application level for session
– Application level for populating list/combos
Session based, application server based, custom code
Chart/Graph Reports Required for creating good looking and user friendly reports Jasper Reports
Connection Pooling Required to improve the performance of database operations in a data centric application Application server based or api from vendor(primrose and many more)
Continuous Integration/Software Configuration Required for Software Configuration management Subversion, Team City
Data tables Required for displaying data table on screen with pagination and other actions Display Tag, GWT, JSF
Database Required for storing application data MySQL, Oracle, SQL Server, Postgres
Defect Tracking Required for defect tracking Excel sheets, Sharepoint tasklist, Bugzilla, JIRA
Logging Required for logging
– different levels.
– different types of output based on log level
Log4j or slf4j, ApacheCommonLogging.
MVC Application request Control and Navigation JSF, Spring webflow, Struts2, or simple JSP/servlet
Page Design/ Inclusion Page inclusion mechanism Tiles
Encryption How to encrypt secret information like passwords Password Hashing or
Multiple level of security, or relying of external system like LDAP for the same.
Persistence Required to persist the data in application (ORM or Normal JDBC) Hibernate, JPA, Ibatis, Spring JDBC Template
Project build/make Automatic build and distribution of application Maven, Ant, Gradle
Tabular Reports Reports Jasper Reports
UI Components and pages UI design JSPs, Flex
Unit test Automated unit testing Junit , HttpUnit
WebServices Exposing application funtionality via web services RESTful webservices,SOAP based Web Services Spring remoting, Axis2, Xfire
XML Processing XML handling JAXP (SAX, DOM), JAXB

Suggestions to improve this list are welcome.

5 Google products I like most

5 Google products I like most

1. Gmail: E-Mail solution from Google

I need not to write much about it, most people know it, truly fast and reliable email solution.

2. Google Alerts: Monitor the Web for interesting new content

You can set alerts for topics/words/things you want to be updated about. Google alert will send
You email with the latest results from web on those keywords.

3. Google Code and Google App Engine : Google Code is Google’s site for developer tools, APIs and technical resources. Run your web apps on Google’s infrastructure. Easy to build, easy to maintain, easy to scale.
You can create apps using Google web tool kit and deploy your application on Google App Engine over the internet and share it with your friends.

4. Google Reader: Google Reader is a Web-based aggregator, capable of reading Atom and RSS feeds online or offline
I like this very much. It helps me organize the blogs you follow. Try using it.

5. Google Map: Lets you see the world, can give directions and distance between two points.
Really help me plan the trips.

Few others which I use are

1. Google Calendar
2. You Tube
3. Blogger
4. Google News
5. Google Finance
6. Google Health
7. Picasa

Naming Strategy in Hibernate – NamingStrategy

Naming Strategy in Hibernate – NamingStrategy

Recently while exploring I Hibernate I came to know very nice feature of Hibernate which gives a handle to map naming convention of underlying tables and columns with the Objects and properties. I found it very interesting and easy to use functionality.

Problem Scenario:
Generally while using hibernate either we keep the tables names corresponding POJO names similar for ease of use or we define the table name in corresponding mapping hbm file. You may come across following different scenarios.
• Sometimes you may need to change the underlying table name or may need to change the naming convention followed in the database schema.
• You may need to have separate tables for different clients using the same application. A typical scenario is the Hosted and multitenant environment.

Code Example
Lets see some mapping example for class and table names in the mapping document
1. Explicitly specified class name and table name
<class name="HelloMessage" table="message" />
2. Table name is missing
<class name="HelloMessage" />
Hibernate default behavior tries to look for table with name HelloMessage in database.

3. Table name is missing
<class name="HelloMessage" />
How I can instruct hibernate to look for TEST_HelloMessage table or Hello_Message Table.

The first two scenarios are very simple. The third item is the scenario where actually NamingStrategy comes into picture. We can provide our instruction for table name and class name mapping to Hibernate.

How to Use NamingStrategy?

Hibernate provides Naming Strategy interface to be implemented by the implementation. I am listed here few methods.
1. String classToTableName(String className) – should return the table name for an entity class.
2. String columnName(String columnName) – handle to alter the column name specified in the mapping document.
3. String tableName(String tableName) – handle to alter the column name specified in the mapping document.
4. String propertyToColumnName(String propertyName) – handle to map property name to column name.

Sample Implementation

* Extending from the DefaultNamingStrategy to
avoid implementing All methods of NamingStrategy interface
public class HelloWorldNamingStrategy
extends DefaultNamingStrategy {
//Extending from the DefaultNamingStrategy to
//avoid implementing All methods of NamingStrategy interface
public String classToTableName(String className) {
//need to get the className only
int dotPos = className.lastIndexOf(".");
String classNameWithoutPackageName
= className.substring(dotPos+1,className.length());
return classNameWithoutPackageName + "_Messages";
public String propertyToColumnName(String propertyName) {
return propertyName;

Mapping Document:

<class name="hello.HelloWorld">
// table name is not mentioned
<id column="MESSAGE_ID" name="id">
<generator class="increment">
<property column="MESSAGE_TEXT" name="text">

Passing Naming Strategy to Hibernate

Configuration conf = new Configuration().configure();

//Passing my own implementation for strategy interface
conf.setNamingStrategy(new HelloWorldNamingStrategy());

//I can use the improved naming strategy provided by hibernate
//conf.setNamingStrategy(new ImprovedNamingStrategy());
sessionFactory= conf.buildSessionFactory();

I have written here very simple implementation of the NamingStrategy, if you see the flexibility here, It can go to any extent. Hibernate itself provides two implementation with name DefaultNamingStrategy and ImprovedNamingStrategy.

Static vs Dynamic Class loading in Java

Dynamic vs Static class Loading
NoClassDefFoundError vs ClassNotFoundException

Today while reading about class loaders I came across very good concept. Which could be a very good question for java interview as well as very good to know concept?

Static loading: When a class is referenced by new operator in the code and the name of the class is known to compiler at the time of compiling the code.

In case of Static Loading: JVM throws the error “NoClassDefFoundError” When it couldn’t find class referenced through new operator (static loading) at run time. This error comes at run time at compile time ref of class was available there could be reason for this as .class file is not available or jvm is not able to load the class because of errors in static block code of the class.

Dynamic Loading: Dynamic loading happens when we refer to a class programmatically. For example by Class.forName () or by using reflection, we use dynamic loading. In this case the name of the class referenced may or may not be known to the compiler at run time.

In Case of Dynamic Loading: A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found.

Sample Code

public class StaticAndDynamicLoading {

public static void main(String args[]) throws Exception {

//static loading.. ref with new object
MyClass obj = new MyClass();

//dynamic loading class name is not known at compile time
//user will pass the class name @ runt ime
Class c = Class.forName(args[1]);



Here are excerpt from java Docs about both the exception.

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
ClassNotFoundException :
Thrown when an application tries to load in a class through its string name using:
• The forName method in class Class.
• The findSystemClass method in class ClassLoader .
• The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.