Should InitialContext instance be cached?

caching, ejb, jakarta-ee, java

Solution

Take in mind that the InitialContext instance is not synchronized, therefore, caching can be dangerous if the same instance is accessed by concurrent threads.

Probably you already know it, but just in case, a common practice that effectively improves the performance of remote method invocation process is caching the ejb reference fetched by the lookup operation.

Problem

I'm using InitialContext in my application to lookup remote EJBs. There are some external systems that notify me about some events and when that happens I delegate this notification to proper remote EJB. I always thought that I should create a new InitialContext for every group of lookups (and maybe even close initial context after these). In above case it's one InitialContext instance per lookup. Although some members of my team are not that sure. So the question is: Should InitialContext instance be cached? If yes then how long should I keep this instance alive and why?

Original source