How to: implement singleton EJB in JBoss

April 7, 2009 at 7:59 am 1 comment

As promised in the rant post – here is the simple and elegant way of creating a singleton bean in JBoss.

public class MySingletonBean implements MySingletonLocal {
  private Object sharedData = new Object();  

  public void workOnSharedData() {
    // TODO do your things here


As you can see, it’s really simple and it looks exactly the same as the @Stateless bean definition except that you replace it with @Service annotation. In order for this to compile you must link with jboss-ejb3-ext-api.jar (found at JBOSS_HOME/common/lib/ directory) during compilation because that annotation is proprietary for JBoss.

Ok, we have the bean – but how we can use it? Well, that’s even easier – just use @EJB annotation the same way you would use it for any regular stateless bean.

public class SingletonUserBean implements SingletonUser {

    @PersistenceContext private EntityManager em;
    @EJB private MySingletonLocal mySingleton;

     // ..... the rest of it


And that’s it – everything will be properly injected for you by the container.

I’ve tested this solution in the JBoss 5.0.1GA – it is supposed to work with older versions as well, but you should try it yourself.

One last note – starting from EJB3.1 spec they are adding @Singleton annotation which is going to be the standard solution for these types of problems. One of the nicer things about it is that they are also adding synchronization support with annotations so we wouldn’t have to deal with it manually (the hard part of singleton beans like that is handling the concurrency issues since it’s shared for all application). And even though it is not part of the spec it is assumed that the new @Singleton beans will be shared in the cluster – so if you have few application servers for high availability or load balancing, you will be able to use this technology to share state between them (for example counting requests for the cluster and not just sinlge server). See more details here.


Entry filed under: Java, Recipies.

The five minute rule Is eye candy underrated?

1 Comment Add your own

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


April 2009
« Feb   Aug »

Most Recent Posts

%d bloggers like this: