Marek
Marek

Reputation: 167

Should InitialContext instance be cached?

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?

Upvotes: 4

Views: 1968

Answers (2)

Gabriel Aramburu
Gabriel Aramburu

Reputation: 2981

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.

Upvotes: 3

Alexander Rühl
Alexander Rühl

Reputation: 6939

Since your IntialContext is nothing else than a reference to the starting point into the namespace, it should not matter whether you do a new each time or store this reference somewhere.

It may only matter if the service provider behind it does a lot of work while initializing and thus decrease your performance if you do it over and over.

Further reading: JNDI trail of Java Tutorial

Upvotes: 2

Related Questions