News Ticker

Singleton Pattern: Java EE implementation

The singleton pattern is one of the most well known design patterns and is used extensively by frameworks such as Spring. Java EE offers an elegant and easy way to implement the singleton pattern. By adding the @Singleton annotation to a class you can turn it into a singleton bean as shown in the following code snippet.

[sourcecode language=”java” toolbar=”false”]
@Singleton
public class SingletonBean {

public String message(){
return "Hello Singleton World!";
}

}
[/sourcecode]

It is important to note that Java EE initialises singleton beans lazily unless annotated with @Startup.

We still have a potential problem with concurrency related method access. Java EE solves this issue rather simply with another set of annotations. By default the container manages concurrency, so an annotation is only required if you want to manage it yourself. This is called bean managed concurrency and is annotated on the class as in the following code snippet.

[sourcecode language=”java” toolbar=”false”]
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@Singleton
public class SingletonBean {

@Lock(LockType.READ)
public String getName(){
return "Return name from Cache";
}

@Lock(LockType.WRITE)
public void addName(String){
// code that adds name to cache
}

}
[/sourcecode]

Further annotations are necessary when this option is chosen. We control access using the familiar read/write concept and annotate methods appropriately as can be seen in the above example.

If you are interested in learning more about how we can develop singletons in ways there were never possible before I suggest that you read chapter 4 of my book Professional Java EE Design Patterns which you can buy from Amazon.

Related articles

 

1 Comment on Singleton Pattern: Java EE implementation

  1. Gustavo Garcia // May 4, 2015 at 04:47 // Reply

    Is the Singleton annotation checked by the Java Runtime or by a specific container/framework like Spring?

Leave a Reply

%d bloggers like this: