How to: implement singleton EJB in JBoss
April 7, 2009
As promised in the rant post – here is the simple and elegant way of creating a singleton bean in JBoss.
@Service
@Local(MySingletonLocal.class)
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.
@Stateless
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.
1 Comment Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1.
ALR | August 20, 2009 at 9:21 am
Worthy of note is the extra complexity introduced by a singleton with regards to concurrency. I fear developers will think, “Oh, only one instance, so it’ll be lean on RAM and thus perform well”.
In truth, mutable state must be dealt with in a Thread-safe manner, which means locking/blocking. So I recommend the @Service/@Singleton for high-read, low-write scenarios.
The example I use is a cache:
http://anonsvn.jboss.org/repos/jbossas/projects/ejb-book/trunk/ch07-rsscache/src/main/java/org/jboss/ejb3/examples/ch07/rsscache/impl/rome/RssCacheBean.java
S,
ALR