viernes, noviembre 03, 2006

After Spring, the Summer Comes

Hello, in blog "After Spring, the Summer Comes", I will summarize interfaces of Spring Core Framework for extending its funcionalities. I'm an active member in Spring Forum, so I have seen some questions about extending funcionalities in Spring or how to modify some behavior of Framework, for this reason I have decided to write down some extension points of Core.

  • First interface is (application/Bean)FactoryAware if your class implements previous interface, and also have an attribute of (application/BeanFactory) and a setter method, Spring will inject the current loaded class. (See 3.3.8 for more information). Moreover it is explained how to avoid the intrusion of Spring into our code.
  • Next interface MethodReplacer is used for changing implementation of a method. Spring will inject new implementation to existing class method. (See for an example).
  • Another interesting interface is org.springframework.beans.factory.config.Scope. Spring 2.0, implements five different scopes, prototype, singleton, request, session, global session. Of course, Spring offers the possibility of creating our scope by implementing Scope interface. In chapter 3.4.4, an example can be found.
  • Two interfaces are provided to control lifecycle of bean. These two interfaces are org.springframework.beans.factory.InitializingBean that are executed after properties of bean are setted, and org.springframework.beans.factory.DisposableBean that is called when container containing the bean is being destroyed. Of course it is better to use next approach, that is using init-method and destroy-method from Spring file, so no Spring dependencies are inserted into our code. This last option is preferred but these two exceptions also exists. (See Chapter 3.5.1).
  • Another interface is org.springframework.beans.factory.BeanNameAware. The BeanFactory will call the bean through this interface to inform the bean of the id it was deployed under. (See for a little description).
  • Next interface BeanPostProcessor is used if you want to do some custom logic after the Spring container has finished instantiating, configuring and otherwise initializing a bean, you can plug in one or more BeanPostProcessor implementations. (See Chapter 3.7.1).
  • The next extension point that we will look at is the org.springframework.beans.factory.config.BeanFactoryPostProcessor. BeanFactoryPostProcessors reads the configuration metadata and potentially change it before the container has actually instantied any other beans. Typical example is PropertyPlaceholderConfigurer, where values injected into a bean are changed for .properties file. (See Chapter 3.7.2 for full information).
  • Next very important interface is org.springframework.beans.factory.FactoryBean. This interface must be implemented by objects that are themselves factories, and you want to use Spring IoC. If you have some complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container. (See Chapter 3.7.3).
  • Spring has events, two interfaces must be implemented ApplicationContext and ApplicationEvent. Every time an ApplicationEvent gets published to the ApplicationContext, that bean will be notified.
  • Spring's Resource interface is meant to be a more capable interface for abstracting access to low-level resources. It is used in Spring and by Spring.
  • Spring's features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.
  • PropertyEditorSupport is a class not interface, but also it is used for extending Spring. PropertyEditors are used for converting String format to the complex type of a property. For example Spring provides LocaleEditor that converts an String value to a Locale class. (In chapter an example is provided).
  • The last class I explain for extending Spring is NamespaceHandler and interface BeanDefinitionParser. Both classes are used for extending basic XML Spring file. You can write your own custom XML bean definition parsers and integrating such parsers into the Spring IoC container. This approach is used by Spring 2.0 for transactions, utils, ... You can create your own definition as is explainde in Appendix B.

Now Summer has become. You have some interfaces to extend Spring Framework so it can adapt to your necessities.

lunes, julio 17, 2006

Offspring matters ....

As you know, in XSD files, there is an attribute to mark an element as abstract. This means that other element will extend it. Typical example of Figure, with Circle, Square, ... as children.

Ok, that's perfect. Imagine you are using XmlBeans (XML binding). You have a list of FigureType, and want to iterate over all figures, and depending its type, make one thing or another (for example drawing the figure). In this case an instanceof approach won't work because in XML Beans we are working with interfaces, not with implementations object, so for example SquareType interface doesn't extends from FigureType interface. So how can we implements the previous example?

Using two thing, one working wiht DOM repesentation instead of object representation, and next using type attribute that all extentended tags require. An example:

<figure type="SquareType" area="c*c" sides="4">

Take a look that the tag is figure but square information is present.

Now let's see the java code to treat this example:

It is as simple as we can imagine:

First we return the DOM representation

final Node node = figureType.getDomNode();

Next we gets the type attribute using DOM library.

final NamedNodeMap nodeAttMap = node.getAttributes();

final String type = nodeAttMap.getNamedItemNS("", "type").getNodeValue();

Remember to change the first parameter of getNameItemNS if namespace of type attribute is changed.

and finally simply a hell if-then-else sequence:

if("SquareType".equals(type)) {

(SquareType) figureType.changeType(SquareType.type));

} else {

Take a look at line inside if; we must cast from FigureType to SquareType using changeType method.

And that's all, simple and easy, only tedious because of if-then-else chain.

martes, julio 11, 2006

Debianizing Java

When you go to to download JDK, you find a disagreeable surprise, only a RPM or a BIN file is found. What's happening if you have a Debin/Ubuntu distribution? Probably you would like to work with a DEB file, but it is not available in java sun site. A simple solution can be done.

First you download the BIN JDK file you want to install. Then using synaptic, you download fakeroot aplication and make-jpkg application. And finally, you apply the next command, fakeroot make-jpkg .bin.

After a few moments you will have a .deb file, so you can install using dpkg tool. After that, because we want to execute by default this new java virtual machine/compiler, execute update-alternatives --config java, and choose the new jdk installed.

And thats all, as simple as you can imagine.

viernes, marzo 17, 2006

Cramer Versus Cramer

Cramer vs Cramer, Java Virtual Machine vs Java Virtual Machine. This article try to give information of what is the best java virtual machine for a given problem. To do this we have choosen two benchmarks so we can give an objective opinion of which are the best virtual machine. There is a lot of benchmarks and a lot of java virtual machines, but we have focused into two virtual machines, Java HotSpot(TM) Client VM (build 1.5.0_05-b05) and IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Linux x86-32 j9vmxi3223-20051103 (JIT enabled), and two benchmarks, JGF Benchmark and Richards and DeltaBlue Benchmark

I would try to explain both benchmarks, but for more information please visit its site.

JGF is composed by three big groups of benchmarks, Sequential Benchmark, Multi-Threaded Benchmark and MPJ Benchmark.

  • The sequential benchmarks, suitable for single processor execution.
  • The multi-threaded benchmarks, suitable for parallel execution on shared memory multiprocessors.
  • The MPJ benchmarks, suitable for parallel execution on distributed memory multiprocessors.

For our porpouse only the first and second benchmarks would be executed.

Sequential Benchmark also have the next subsections:

  • Arith: execution of arithmetic operations
  • Assign: variable assignment
  • Cast: casting
  • Create: creating objects and arrays
  • Loop: Loop overheads
  • Math: execution of maths library operations
  • Method: method invocation
  • Serial: Serialisation
  • Exception Exception handling
  • Serial: Read/Write Lists
  • Method: executing methods in same object or foreign object

  • Series: Fourier coefficient analysis
  • LUFact: LU Factorisation
  • SOR: Successive over-relaxation
  • HeapSort: Integer sorting
  • Crypt: IDEA encryption
  • FFT: FFT
  • Sparse: Sparse Matrix multiplication

  • Search: Alpha-beta pruned search
  • Euler: Computational Fluid Dynamics
  • MD: Molecular Dynamics simulation
  • MC: Monte Carlo simulation
  • Ray Tracer: 3D Ray Tracer

Multi-Thread Benchmark also have the next subsection:

  • ForkJoin: forking and joining threads
  • Barrier: barrier synchronisation
  • Sync: synchronized blocks and methods
  • Series: Fourier coefficient analysis
  • LUFact: LU Factorisation
  • SOR: Successive over-relaxation
  • Crypt: IDEA encryption
  • Sparse: Sparse Matrix multiplication

  • MolDyn: Molecular Dynamics simulation
  • MonteCarlo: Monte Carlo simulation
  • RayTracer: 3D Ray Tracer

At the heart of Richards is a task dispatcher (Richards.schedule). Tasks come in 4 different flavors, each represented by a class (DeviceTask, HandlerTask, IdleTask, WorkTask, all subclasses of Task). Each kind of task has an associated work function (fn). At startup (, a particular task mix is created, and then the tasks are scheduled, each having its work function invoked. The work functions manipulate work packets and packet queues. At the end of the benchmark (in the number of queued and held packets is checked against the correct value to assist in verifying that the benchmark ran correctly.

For our pourpouse we have executed all sequential benchmark. And only the first group of multi-thread becnhmark. Also, we have runned Richards Benchmark.

All this benchmarks has been runned on a Pentium IV 3 GHz and 512 MB RAM, on Ubuntu Linux 5.10. The optional arguments for java command has been -Xms256m -Xmx512m because there is some tests that needs as memory as possible or a RuntimeException would be thrown.

Lets see the results of the first section of sequencial benchmark.

In this graph we can see that for mathematical operations is faster Java HotSpot than IBM. IBM Java Virtual Machine only wins in creations of objects and rounding numbers, in all other operations, like managing lists, arrays or casting is better Java HotSpot.

About section 2 in sequencial benchmark, we can see that we have the same tests but with three different results, that is because the size of data increases in every test. See JGF homepage to see how the values increases because there is no standard growth between the tests.

We can say that in all tests Java HotSpot is much faster that IBM JVM, this is because HotSpot is better in numerical problems than IBM Java Virtual Machine.

Although the differences has been minimized, Java HotSpot is faster than IBM JVM.

When the load is heavy, IBM JVM in some tests are faster than Java HotSpot, surely we can say that IBM JVM manages memory data better than Java HotSpot.

Now, let's do the same, but with the second group of benchmarks, remember that only the first group, because we are not interested in knowing how fast is a JVM executing mathematical operations in parallel, because we have already executed when I was executing sequential, what we really wants to know is which Java Virtual Machine manages the threads faster.

As we can see, with only one thread, in this case (and all future cases), IBM Virtual Machine is faster than Sun Java HotSpot. See that synchronizers in IBM is spectacular in comparision to Java HotSpot.

Note that in forkjoin a negative value is calculated. I have tried three times the same test and with one thread, always the result has been negative. I think that an overfload has been produced. Of course it is impossible a negative count of forkjoins.

With two threads, the difference between both JVM has been reduced in three first tests, but in synchronizations, IBM still be the best ione in difference.

With 5 , 10 and 20 threads happens the same as 2 threads. IBM still being faster than Java HotSpot.

Finally, although first tests sun VM is faster than IBM, we can say but that with a lot of threads synchronizating, IBM VM is faster than sun VM.

In summary, in thread environment like web servers, IBM JVM seems to be better than SUN VM. On the other hand, SUN VM in standard applications offer a better throughput.