Can we make an EJB singleton?

Q

Can we make an EJB singleton?

✍: Guest

A

This is a debatable question, and for every answer we propose there can be contradictions. I propose 2 solutions fo the same. Remember that EJB's are distributed componenets and can be deployed on different JVM's in a Distributed environment
i) Follow the steps as given below
Make sure that your serviceLocator is deployed on only one JVM.
In the serviceLocator create a HashTable/HashMap(You are the right judge to choose between these two)
When ever a request comes for an EJB to a serviceLocator, it first checks in the HashTable if an entry already exists in the table with key being the JNDI name of EJB. If key is present and value is not null, return the existing reference, else lookup the EJB in JNDI as we do normally and add an entry into the Hashtable before returning it to the client. This makes sure that you maintain a singleton of EJB.
ii) In distributed environment our components/Java Objects would be running on different JVM's. So the normal singleton code we write for maintaining single instance works fine for single JVM, but when the class could be loaded in multiple JVM's and Instantiated in multiple JVM's normal singleton code does not work. This is because the ClassLoaders being used in the different JVM's are different from each other and there is no defined mechanism to check and compare what is loaded in another JVM. A solution could be(Not tested yet. Need your feedback on this) to write our own ClassLoader and pass this classLoader as argument, whenever we are creating a new Instance and make sure that only one instance is created for the proposed class.This can be done easily.

2013-03-18, 1940👍, 0💬