Wednesday, February 01, 2006

Singleton Patterns

Question
The Singleton pattern is not permitted by the J2EE spec, so How can I cache EJB home interfaces across EJBs in my application and avoid having each EJB get its own home interfaces?

Answer
This is one of those grey areas in the J2EE spec. Yes, it's true that theoretically, static objects (hence, singleton patterns) are not permitted. This is because you never know how many class loaders there are in your ejb container - unless you know the inner working of your container. Therefore, the singleton object will be unique in the class loader only. If there are multiple class loaders, your singleton object will exist more than once (1 instance per class loader). However, if you are ready to accept the fact that your ejb stub may be cached multiple times (as much as once in every class loader), the singleton pattern will still work.
Ithe ejb container's responsibility to cache ejb stubs. However, some implementation of jndi are very slow to lookup. Repeatedly performing jndi lookups can actually slow down your app considerably. In fact, I have written that exact singleton class you are contemplating and this has increased performance.

Thanks Nick Maiorano and Alex jguru-Jan 30, 2003