Monday, January 3, 2011

Java JMX tutorial

Here is some sample Java source code for some JMX tests that I created recently.

First, here's the source code for a Java MBean interface named HelloMBean:

public interface HelloMBean {

public String helloService(String name);

}

A class to implement the JMX MBean interface
Next, here's the source code for a Java class named Hello that implements the HelloMBean interface we just defined:

public class Hello implements HelloMBean {

@Override
public String helloService(String name) {

System.out.println(" Called ...");
return " Hello Mbean :"+name;
}

}

A JMX example class (a JMX service)
Next up, here's the source code for a Java class named SimpleAgent that includes a main method that starts up our JMX service application:

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;


public class SimpleAgent {


private MBeanServer mbs = null;

public SimpleAgent() {

// Get the platform MBeanServer
mbs = ManagementFactory.getPlatformMBeanServer();

// Unique identification of MBeans
Hello helloBean = new Hello();
ObjectName helloName = null;

try {
// Uniquely identify the MBeans and register them with the platform MBeanServer
helloName = new ObjectName("FOO:name=HelloBean");
mbs.registerMBean(helloBean, helloName);
} catch(Exception e) {
e.printStackTrace();
}
}
// Utility method: so that the application continues to run
private static void waitForEnterPressed() {
try {
System.out.println("Press to continue...");
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String argv[]) {
SimpleAgent agent = new SimpleAgent();
System.out.println("SimpleAgent is running...");
SimpleAgent.waitForEnterPressed();
}
}

A script to start our JMX service
And finally here's a Unix/Linux shell script named run.bat that I wrote to run this sample JMX application ("JMX service")

Run.bat
java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=5555 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false SimpleAgent

As you can see from that code, my application will listen on port 5555 of whatever computer system it is run on.




Access our JMX service with JConsole
Once the application is running you can then connect to it with the jconsole application and view its JMX resources.



test your mbean by passing args.

Tuesday, December 21, 2010

Software Design Principles Part II

Open Close Principle

Motivation

A clever application design and the code writing part should take care of the frequent changes that are done during the development and the maintaining phase of an application. Usually, many changes are involved when a new functionality is added to an application. Those changes in the existing code should be minimized, since it's assumed that the existing code is already unit tested and changes in already written code might affect the existing functionality in an unwanted manner.

The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Intent

Software entities like classes, modules and functions should be open for extension but closed for modifications.

Example

Bellow is an example which violates the Open Close Principle. It implements a graphic editor which handles the drawing of different shapes. It's obviously that it does not follow the Open Close Principle since the GraphicEditor class has to be modified for every new shape class that has to be added. There are several disadvantages:

· for each new shape added the unit testing of the GraphicEditor should be redone.

· when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.

· adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly

In order to have more dramatic effect, just imagine that the Graphic Editor is a big class, with a lot of functionality inside, written and changed by many developers, while the shape might be a class implemented only by one developer. In this case it would be great improvement to allow the adding of a new shape without changing the GraphicEditor class.

Open Close Principle(OCP) - bad

// Open-Close Principle - Bad example
class GraphicEditor {

public void drawShape(Shape s) {
if (s.m_type==1)
drawRectangle(s);
else if (s.m_type==2)
drawCircle(s);
}
public void drawCircle(Circle r) {....}
public void drawRectangle(Rectangle r) {....}
}

class Shape {
int m_type;
}

class Rectangle extends Shape {
Rectangle() {
super.m_type=1;
}
}

class Circle extends Shape {
Circle() {
super.m_type=2;
}
}

Bellow is a example which supports the Open Close Principle. In the new design we use abstract draw() method in GraphicEditor for drawing objects, while moving the implementation in the concrete shape objects. Using the Open Close Principle the problems from the previous design are avoided, because GraphicEditor is not changed when a new shape class is added:

· no unit testing required.

· no need to understand the sourcecode from GraphicEditor.

· since the drawing code is moved to the concrete shape classes, it's a reduced risk to affect old functionallity when new functionallity is added.

Open Close Principle(OCP) - good

/ Open-Close Principle - Good example
class GraphicEditor {
public void drawShape(Shape s) {
s.draw();
}
}

class Shape {
abstract void draw();
}

class Rectangle extends Shape {
public void draw() {
// draw the rectangle
}
}

Conclusion

Like every principle OCP is only a principle. Making a flexible design involves additional time and effort spent for it and it introduce new level of abstraction increasing the complexity of the code. So this principle should be applied in those area which are most likely to be changed.

There are many design patterns that help us to extend code without changing it. For instance the Decorator pattern help us to follow Open Close principle. Also the Factory Method or the Observer pattern might be used to design an application easy to change with minimum changes in the existing code.

Software Design Principles Part I

Design Principles

> What are Software Design Principles?

Software design principles represent a set of guidelines that helps us to avoid having a bad design. The design principles are associated to Robert Martin who gathered them in "Agile Software Development: Principles, Patterns, and Practices". According to Robert Martin there are 3 important characteristics of a bad design that should be avoided:

Rigidity - It is hard to change because every change affects too many other parts of the system.
Fragility - When you make a change, unexpected parts of the system break.
Immobility - It is hard to reuse in another application because it cannot be disentangled from the current application.

Open Close Principle

Software entities like classes, modules and functions should be open for extension but closed for modifications.
OPC is a generic principle. You can consider it when writing your classes to make sure that when you need to extend their behavior you don’t have to change the class but to extend it. The same principle can be applied for modules, packages, libraries. If you have a library containing a set of classes there are many reasons for which you’ll prefer to extend it without changing the code that was already written (backward compatibility, regression testing, …). This is why we have to make sure our modules follow Open Closed Principle.

When referring to the classes Open Close Principle can be ensured by use of Abstract Classes and concrete classes for implementing their behavior. This will enforce having Concrete Classes extending Abstract Classes instead of changing them. Some particular cases of this are Template Pattern and Strategy Pattern.

Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Dependency Inversion Principle states that we should decouple high level modules from low level modules, introducing an abstraction layer between the high level classes and low level classes. Further more it inverts the dependency: instead of writing our abstractions based on details, the we should write the details based on abstractions.

Dependency Inversion or Inversion of Control are better know terms referring to the way in which the dependencies are realized. In the classical way when a software module(class, framework, …) need some other module, it initializes and holds a direct reference to it. This will make the 2 modules tight coupled. In order to decouple them the first module will provide a hook(a property, parameter, …) and an external module controlling the dependencies will inject the reference to the second one.

By applying the Dependency Inversion the modules can be easily changed by other modules just changing the dependency module. Factories and Abstract Factories can be used as dependency frameworks, but there are specialized frameworks for that, known as Inversion of Control Container.

Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they don't use.
This principle teaches us to take care how we write our interfaces. When we write our interfaces we should take care to add only methods that should be there. If we add methods that should not be there the classes implementing the interface will have to implement those methods as well. For example if we create an interface called Worker and add a method lunch break, all the workers will have to implement it. What if the worker is a robot?

As a conclusion Interfaces containing methods that are not specific to it are called polluted or fat interfaces. We should avoid them.

Single Responsibility Principle

A class should have only one reason to change.
In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes.

Single Responsibility Principle was introduced Tom DeMarco in his book Structured Analysis and Systems Specification, 1979. Robert Martin reinterpreted the concept and defined the responsibility as a reason to change.

Liskov's Substitution Principle

Derived types must be completely substitutable for their base types.
This principle is just an extension of the Open Close Principle in terms of behavior meaning that we must make sure that new derived classes are extending the base classes without changing their behavior. The new derived classes should be able to replace the base classes without any change in the code.

Liskov's Substitution Principle was introduced by Barbara Liskov in a 1987 Conference on Object Oriented Programming Systems Languages and Applications, in Data abstraction and hierarchy

Wednesday, November 17, 2010

Java 5 : Extended

This page describe the major new features added in Java 5.

Annotations (Metadata)

avoids need for external configuration files, allowing configuration data to be embedded in source files
avoids duplicated boilerplate code by enabling tools to generate it from annotations in source code
leads to a declarative programming style
an example of a specific annotation added in Java 5 is @Override which marks a method that overrides a superclass method
for more information, see here
Autoboxing/Unboxing

avoids need to convert between primitives and their corresponding type wrapper objects
basic example
int i = 19;
Integer iObj = i;
int j = iObj;
// i and j are equal
collections example
List list = new ArrayList(); // see "Generics"
int i = 19;
list.add(i);
int j = list.get(0);
// i and j are equal
overuse can result in performance issues
for more information, see here
Enhanced For Loop

array example
Car[] cars = new Car[](5);
// populate array of Car objects
for (Car car : cars) {
// Use the variable car inside the loop.
}
list example
List cars = new ArrayList() // see "Generics"
// populate List of Car objects
for (Car car : cars) {
// Use the variable car inside the loop.
}
for more information, see here
Enums

can create enumerated types with arbitrary fields and methods
example
enum Season { WINTER, SPRING, SUMMER, FALL }
Season season = SPRING;
for (Season season : Season.values()) {
// use season variable
}
to get the integer value of an enumerated value, invoke the ordinal method on it
for more information, see here (includes an example of adding fields and methods to enums)
Generics

most often used for type-safe collections
example
List myList = new ArrayList();
// only String objects can be added to myList.
collections of subclass objects can be passed to methods that accept collections of superclass objects (for example, an object of type List can be passed to a method that accepts List or even List)
for more information, see here
Static Import

avoids the need to qualify static members of classes or interfaces with the class or interface name
example from JUnit 4
import static org.junit.Assert.*;
// can now use static assert methods from the Assert class
// without prefixing them with "Assert."
note that the ".*" part says to import all the static members from the Assert class (can't omit that!)
for more information, see here
Varargs

eliminates the need to put arguments into an array for the purpose of passing a variable number of arguments to a method
example
public void washCars(Car... cars) {
for (int i = 0; i < cars.length; i++) {
Car car = cars[i];
// wash the car
}
}

// call like this
washCars(car1, car2, car3);
the type of cars is Car[]

Tuesday, November 9, 2010

LOG4J :Best Practice

I’ve seen these antipatterns over and over again, and I thought it was time to write about them to help any folks who are new to Log4J out there. Senior developers – please share this with your junior peers and save yourself the pain of refactoring later! I’m interested in common mistakes or points of confusion that you’ve seen as well.

Read on to get a quick tutorial, or reference to point your developers at…


Mistake 1: Not logging exceptions at all

Many times, developers don’t realize that there are overloaded versions of the basic log4j methods. I have seen this more times than I can count:

catch(SomeMeaningfulException e) {
LOG.error("Bad things: " + e.getMessage());
}
Why is this bad? Because you just lost the single most valuable piece of information in the exception: the stack trace! Obviously, a well-thought out exception strategy is ideal, but at the very least, do this:

LOG.error("Bad things",e);

Mistake 2: Not logging exceptions with the correct method

catch(SomeMeaningfulException e) {
LOG.error("Bad things");
LOG.error(e);
}
This is a tricky one. The single-parameter method signature for log4j will simply call toString on the object passed in. In the case of a Throwable, this means you will get the output of getMessage; thus you have exactly the same result as in #1.

Mistake 3: Not adding thread name to PatternLayout

Many, many sample log4j configuration files to be found on the net (such as this example) exclude the crucial thread name property (%t). This is absolutely required when using log4j in any kind of multi-user environment. Without it (and without smart alternative use of something like the MDC/NDC functionality), it’s impossible to trace a series of log statements to a single, consecutive, series of actions — for example, a user request in most modern web frameworks.

Make sure you include the %t conversion parameter if you’re running in any multi-user environment!

Mistake 4: Not making appropriate use of log categories

It’s very common to use the typical fully qualified class name as the name of the Category you log to:

static Logger LOG = Logger.getLogger(ThisClass.getClass());
This is all well and good, but suffers from 2 flaws:

Developers tend to copy and paste this boilerplate code from one class to another. Since the class names are often hard-coded in the static initializer, this is a pattern that is extremely vulnerable to copy-and-paste errors. Java unfortunately doesn’t allow ‘this’ in a static context, and doesn’t have an alternative way to refer to “the current Class”.
It doesn’t offer logical organization, especially for API providers. One of the brilliant things that the Hibernate team did in their use of logging is that, in addition to FQCN-named loggers, they identified a series of key “logical” logging categories that abstracted common logging use cases into simple categories (most notably logging of all SQL statements, which can happen in many different classes using the same logical category.
There are various tricks to avoid this scenario.

Checkstyle can look for common log4j antipatterns. You’re using checkstyle anyway, right?
You can create a logger factory which will look on the call stack for the current class name (as shown here).
You can use smart annotations or DI (such as is easily done with Guice) to annotate your Loggers and fill in at runtime.

Mistake 5: Not understanding how (or where) log4j is configured

It’s amazingly common for developers not to know how to configure log4j, or even know where to start to set it up. I personally have answered many, many questions from both co-workers and forum / mailing list folks who can’t figure out how to get started with log4j. Usually this is in conjunction with 3rd party libraries like Spring or Hibernate, running in a web application.

Admittedly, the log4j documentation is not super clear on this subject, and I will attempt to cover the very common scenarios that I have seen confuse developers.

If you are running in a web application, generally the log4j configuration file will go in WEB-INF/classes. If you are building in Eclipse, you can explicitly create this directory, or (in some versions of Eclipse) place it in your Java source root directory and it will go to the right place.
If you are running in a console application, the log4j configuration file must be somewhere on your CLASSPATH.
You need to have log4j configuration defined in a file called log4j.xml (using the DOMConfigurator syntax), or log4j.properties (using the PropertyConfigurator syntax).

Reference: log4j Default Initialization Procedure

Tuesday, October 5, 2010

Eclipse Java Autocompletion Not Working

Try restoring the default options in 'Windows > Preferences > Java > Editor > Content Assist > Advanced'

Select all in the content table .

now you have done with code completion.

Monday, August 16, 2010

Java Threads : Volatile vs Synchronized

This can be best understood by looking at the effects that volatile & synchronized on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

int i1; int geti1() {return i1;}

volatile int i2; int geti2() {return i2;}

int i3; synchronized int geti3() {return i3;}


geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it’s thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a “main” memory, and this is the memory that holds the current “correct” value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the “main” memory. So in fact, it is possible for the “main” memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to “main” memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from “main” memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory. Effectively, a variable declared volatile must have it’s data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than “plain” variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That’s the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with “main” memory. So executing geti3() does the following:

The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
The thread memory flushes all its variables, i.e. it has all of its variables effectively read from “main” memory (JVMs can use dirty sets to optimize this so that only “dirty” variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from “main” memory).
(Any changes to variables would normally now be written out to “main” memory, but for geti3() we have no changes.)
The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and “main” memory, synchronized synchronizes the value of all variables between thread memory and “main” memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

Using the volatile keyword ensures that the variable is never kept in a register. This

guarantees that the variable is truly shared between threads.


Synchronization boundaries signal to the virtual machine that it must invalidate its registers.

When the virtual machine enters a synchronized method or block, it must reload data it has cached in its local registers. Before the virtual machine exits a synchronization method or block, it must store its local registers to main memory.