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?

Nick Maiorano

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.

Anyway, those are the facts. It's up to you to decide if you want to remain "J2EE pure" or make a deal with the devil. ;-)

[Alex: Also check the comments on this FAQ: Can a bean act as a singleton to provide logging and other services?]