2

Currently I am using EJB3.0 session beans in my application. Normally i lookup the bean using jndi name and call the concerned method. But recently what I was suggested to store these references in a Map rather than looking up again and again.

Is this a good practice to store Session Bean references into Map to avoid their lookup every time ? Or is it Hazardous ? What kind of problems if at all application may have to encounter ?

If it is a good practice then I have another concern.

Class that contains Map to store references is part of Module A. While session beans are part of Module B1 ...Bn. So Once after looking up when I store the reference in Map, I can retrieve it back. In the meantime Module Bn is redeployed but A remains as it is. So now after looking up the bean from the Map ( as it contains entry) using it, ClassCast Exception is thrown.

What is the reason of that and how can I avoid ? I am using JBOSS Application server - jboss 5.1.0.GA

SacJn
  • 777
  • 1
  • 6
  • 16

1 Answers1

1

It is fine to cache references to stateless and singleton session bean lookups. That's basically what the @EJB annotation does when you use it on a field. (It obviously does not work for stateful session beans, which return a distinct EJB reference for each lookup.)

You didn't mention your application server and didn't provide a stack trace for the ClassCastException, but restarting a module very likely creates a new class loader for the new instance of the application, which means the EJB references that you have cached are now incompatible. I would have guessed a similar ClassCastException would happen even if you didn't cache the result, but perhaps your application server has a workaround for that. It's probably best to restart all caller modules (or just the entire application) when restarting EJB modules.

Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • Yeah, I did not post logs because it happened a long back and since then I am not using caching. So does that mean if I am using **`@EJB`** annotation over my field, Its just redundant to cache these references ? And yes when I don't use cache , after reloading of module fresh loopup of bean works without any problem. Your class loader theory seems convincing but is **`ClassCastException`** most appropriate in these cases. Or may be when reload a module, its pool of references is erased by application server maintained with it and fresh one is created – SacJn Oct 12 '15 at 03:54