Monday, April 13, 2009

Using the Singleton Design Pattern in a multithreaded environment

Let's take a look first at the definition of the Singleton Pattern.

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Here the implementation of this definition :

public class Singleton {

/** The unique instance **/
private static Singleton instance;

/** The private constructor **/
private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

There is a problem with the code above in a multithreaded environment. Two threads might get ahold of two different instances if they enter at same time in the getInstance method.

So how to deal with multithreading ?

This problem can be fixed using the synchronized keyword.

public class Singleton {

/** The unique instance **/
private static Singleton instance;

/** The private constructor **/
private Singleton() {}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

The getInstance method is now synchronized so we force every threads to wait its turn before it can enter the method. This solution fixes our problem but it is very expensive. Indeed we only need synchronization for the first call. After that synchronization is totally unneeded. Remember that synchronization decreases performance by a factor of 100.

A solution consists of relying on the JVM to create our instance when the class is loaded. You can use this solution if the overhead of the creation and runtime aspects of the singleton are not onerous.

public class Singleton {

/** The unique instance **/
private static Singleton instance = new Singleton();

/** The private constructor **/
private Singleton() {}

public static Singleton getInstance() {
return instance;
}
}
Since Java 1.5, there is a new approach to implement Singletons. Simply make it an enum type :

public enum Singleton {

INSTANCE;

//Singleton method
public void someMethod( ) {...}
}
Accessing the enum singleton :
Singleton.INSTANCE.someMethod( );

If you don't want to automatically create an instance of your singleton when the JVM start, there is another solution called "double-checked locking". With this solution, we first check to see if an instance is created and only then we synchronize. This way we only synchronize the first call and there's no performance issue anymore. Another requirement is to use the volatile keyword for the Singleton instance.

public class Singleton {

/** The unique instance **/
private volatile static Singleton instance;

/** The private constructor **/
private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}

return instance;
}
}

!!! This solution will not work in Java 1.4 or earlier. Many JVMs in Java version 1.4 and earlier contains implementation of the volatile keyword that allow improper synchronization fo double checed locking.

Here's an interresting article on the double-checked locking pattern and the use of the volatile keyword.

Another article in french.

Sunday, April 12, 2009

How to validate a XML document from a XML schema using javax.xml.validation.Validator

Since 1.5, you can validate a XML document from a XML schema using the javax.xml.validation.Validator object.

Here's a snippet of code showing how to use this validator.

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;


public class Main {

/**
* Will throw a SAXException if the XML document is not valid
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {

String xml = "...";

//XML parsing
DocumentBuilderFactory docBuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docBuilderfactory.newDocumentBuilder();

InputStream is = new ByteArrayInputStream(xml.getBytes());
Document xmlDocument = builder.parse(is);
xmlDocument.getDocumentElement().normalize();

//XSD parsing
File xsd = new File("src/main/resources/xsd/yourXsd.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsd);

//Validation
javax.xml.validation.Validator validator = schema.newValidator();
Source source = new DOMSource(xmlDocument);
validator.validate(source);
}
}

This validator is very verbose. In a real application, a good practice is to create a component encapsulating the code above.

Sunday, April 5, 2009

Dependencies injection with Spring annotations (@Repository, @Service, @Autowired)

One of the big downfall with frameworks relying on XML configurations file is that they are not synchronized with your code. For example, if you are doing a refactoring of your code like renaming a package or a class, you need to update your XML files too. If you're not, you will end up with a configuration exception at runtime.

Spring 2.5 introduces injection dependencies by annotation with stereotypes annotation like @Repository, @Service, etc... and the @Autowired annotation.

Here's how you define your beans the old school way :

applicationContext.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="beanDAO_1" class="com.yourcompany.dao.BeanDAO_1_Impl"/>
...
<bean id="beanDAO_N" class="com.yourcompany.dao.BeanDAO_N_Impl"/>

<bean id="beanServices_1" class="com.yourcompany.services.BeanServices_1_Impl">
<property name="beanDAO_1" ref="beanDAO_1"/>
</bean>
...
<bean id="beanServices_N" class="com.yourcompany.services.BeanServices_N_Impl">
<property name="beanDAO_N" ref="beanDAO_N"/>
</bean>

</beans>

BeanDAO_1_Impl.class :

package com.yourcompany.dao.impl;

public class BeanDAO_1_Impl implements BeanDAO_1 {
...
}

BeanServices_1.class :

package com.yourcompany.services.impl;

public class BeanServices_1_Impl implements BeanServices_1 {
private BeanDAO_1 beanDAO_1;
...
public setBeanDAO_1(BeanDAO_1 beanDAO_1) {
this.beanDAO_1 = beanDAO_1;
}
}


Here's how you define your beans with spring annotations :

applicationContext.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"/>

<context:component-scan base-package="com.yourcompany.dao.impl"/>
<context:component-scan base-package="com.yourcompany.services.impl"/>
</beans>

BeanDAO_1_Impl.class :

package com.yourcompany.dao.impl;

@Repository("beanDAO_1")
public class BeanDAO_1_Impl implements BeanDAO_1 {
...
}

BeanServices_1.class :

package com.yourcompany.services.impl;

@Service("beanServices_1")
public class BeanServices_1_Impl implements BeanServices_1 {
@Autowired
private BeanDAO_1 beanDAO_1;
//No need of a setter anymore. Spring can inject the beanDAO_1
//even if it's a private properties
}

And that's how it's done... No more big XML configuration files.

Consult the spring documentation for a detailed explanation of the differences between the annotation sterotypes (@Repository, @Services, @Component ...)

Saturday, April 4, 2009

Object validation by annotations with the OVal framework

OVal is a validation framework for any kind of java objects. For example when you want to validate a JavaBean you just have to annotate its properties like this :


public class object {
@NotNull
@NotEmpty
@Length(max=32)
private String name;
}

To process the validation just call the OVal validator :

net.sf.oval.Validator validator = new net.sf.oval.Validator();
List violations = validator.validate(obj);

if(!violations.isEmpty())
{
//Do whatever you want
}

In a real world application you need sometimes to return an error code to the client depending on the error type. Do not worry, OVal is doing it for you. Just add the error code property in your annotations like this

public class object {
@NotNull(errorCode="46")
...
private String name;
}

You can retrieve the error code in each ConstraintViolation object with the getErrorCode() method.

OVal does not only validate JavaBeans.

By utilizing AspectJ, OVal provides support for several aspects of programming by contract - however it is not a full blown programming by contract implementation.

With OVal you can

  • enforce that a parameterized constructor/method is invoked only if the given arguments satisfy prior defined constraints (precondition)

  • enforce that a method is invoked only if the object is in a certain state (precondition/invariant)

  • enforce that the return value of a method must satisfy prior defined constraints (postcondition)

  • enforce that the object must be in a certain state after a method has been executed (postcondition/invariant)


I suggest you read the user guide for more detailed examples.

Here is the list of the OVAL annotations :
Assert Check if evaluating the expression in the specified expression language returns true.
AssertConstraintSet Check if the value satisfies the all constraints of specified constraint set.
AssertFalse Check if the value is false.
AssertFieldConstraints Check if the value satisfies the constraints defined for the specified field.
AssertTrue Check if the value is true.
AssertURL Check if the value is a valid URL.
AssertValid Check if the value passes a validation by Validator.validate().
CheckWith Check the value by a method of the same class that takes the value as argument and returns true if valid and false if invalid.
CheckWithMultiple Check the value with the given CheckWith constraints.
DateRange Check if the date is within the a date range.
EqualToField Check if value equals the value of the referenced field.
Future Check if the date is in the future.
HasSubstring Check if the string contains a certain substring.
InstanceOf Check if the value is an instance of the specified class or implements all specified interfaces.
InstanceOfAny Check if the value is an instance of the specified class or implements one of the specified interfaces.
Length Check if the string representation has certain length.
MatchPattern Check if the specified regular expression pattern is matched.
Max Check if the number is smaller than or equal to X.
MaxLength Check if the string representation does not exceed the given length.
MaxSize Check if an array or collection does not exceed the given size.
MemberOf Check if the string representation is contained in the given string array.
Min Check if the number is greater than or equal to X.
MinLength Check if the string representation has at least the given length.
MinSize Check if the array or collection has at least the given number of elements.
NoSelfReference Check that the value is not a reference to the validated object itself.
NotBlank Check if the string representation is not empty and does not only contain white spaces.
NotEmpty Check if the string representation is not empty ("").
NotEqual Check if the string representation does not equal a given string.
NotEqualToField Check if value does not equal the value of the referenced field.
NotMemberOf Check if the string representation is not contained in the given string array.
NotNegative Check if the number is greater or equal zero.
NotNull Check if not null.
Past Check if the date is in the past.
Range Check if the number is in the given range.
Size Check if the array or collection has the given size.
ValidateWithMethod Check the value by a method of the same class that takes the value as argument and returns true if valid and false if invalid.


First post

I called my blog java hell for a simple reason. Since I began developing in Java, things are getting more and more complicated along the way. Frameworks like Spring, hibernate, EJBs and others appeared. At the beginning, They were designed to simplify our work but in the end people tends to use them even for simple things. Moreover these frameworks are far from perfect and sometimes they are difficult to use due to their complexity and the lack of real examples or documentation.

I will share in this blog my experience in software development in order to help people to not make the same errors I did.