Wednesday, June 9, 2010

There can be only one

Before Java release 1.5 you had to do the following to create a Singleton:

public class ImASingleton {

private static final ImASingleton INSTANCE = new ImASingleton();

private ImASingleton() {
}

public static ImASingleton getInstance() {
return INSTANCE;
}
}

And to be able to serialize this singleton, you had to do 3 things:
1. Implement the Serializable interface.
2. Mark the instance fields transient if you didn't want them to be serialized.
3. Define a readResolve() method to return the single instance. This is a hook method called in the deserialization process. If you don't provide this method, the default implementation will always create a new instance in stead of your unique instance!

public class ImASingleton implements Serializable {

private static final ImASingleton INSTANCE = new ImASingleton();
private final transient Object nonSerializableField;

private ImASingleton() {
}

public static ImASingleton getInstance() {
return INSTANCE;
}

private Object readResolve() {
return INSTANCE;
}
}

As of Java 1.5 the preferred way to create a singleton is simply by using an enum. This get's you the Serialization for free.


public enum MySingleton() {
INSTANCE;
}

Friday, June 4, 2010

I want it now

On my current project I'm amongst others doing JSF front-end development again. An older module of the project combines JSF with jsp's and a more recent one with facelets (xhtml). During my first front end story, I was confronted with a JSF attribute that I, either used to understand and forgot, or never really got at all: The 'immediate' attribute.

In contrary to what a lot of developers think (myself included untill I read the article), the immediate flag does not skip the 'Process Validations' phase. It causes a component to be processed in the 'Apply Request Values' phase. This is the second life cyle phase in stead of the third.

Even for developers who completely understand it, it seems difficult to explain in a clear manner. I found a good article summarizing the use cases for it: http://wiki.apache.org/myfaces/How_The_Immediate_Attribute_Works