views:

62

answers:

1

When you want to call an EJBBean from the client, first you need to get hold of an EJBHome object reference through JNDI lookup. This code needs to be executed each time you need to work with the EJBBean so is gets redundant and expensive.

To solve this problem, you can cache the EJBHome object references and reuse them again and again from the cache without repeating the JNDI lookup.

This is the EJBHomeFactory Pattern (or a more generic Service Locator Pattern).

The majority of implementations I have seen use a synchronized Map as the cache, or a Hashtable. If the cache is constructed when the application is deployed on the server and no modifications are made to the cache afterwards (only get() methods are performed) do I really need a synchronized Map or a HashMap will do?

I know HashMap is not safe if at least one of the threads modifies the map (there is even a SO post on this here) but in this case threads only perform reads.

So, is a HashMap safe to use in the EJBHomeFactory Pattern?

+1  A: 

If you can guarantee the life-cycle is as you describe it seems clear that the unsynchronized HashMap should be OK. However, my instinct is that this is building in a brittle dependency on your current deployment pattern.

If you use a synchronized datastructure then you know it's safe now and in the future. Unless you have concrete evidence that the synchronisation is truly impacting performance I would go with the "obviously correct" implementation.

In passing, several leading app servers actually cache the results of JNDI lookups so it's not clear how much saving the pattern your using actually gives - though I must admit I do tend to use it myself.

EJB references themselves can be reused, so in fact the frequency of going to the home can be kept quite low. If extreme performance is the objective this may be a further avenue to explore.

djna