In this tip, we'll look at some of the most common JNDI optimizations. In particular, we'll show you how to combine the cache and generic helper classes to create a factory-style solution for JNDI overhead.
Reducing context instances
Listing 1 shows a typical EJB code that requires multiple JNDI lookups. Take a moment to study the code, and then we'll optimize it to get better performance.
Listing 1. A typical EJB lookup
public boolean buyitems (Paymentinfo paymentinfo, String storename,
List items) {
//Load up initial C Ontext
Context ctx = new InitialContext ();
//Look up a Bean´s home interface
Object obj = Ctx.looku P ("Java:comp/env/ejb/purchasehome");
Purchasehome purchasehome =
(purchasehome) portableremoteobject.narrow (obj, purchasehome.class);
Purchase Purchase = purchasehome.create (Paymentinfo);
//Work on the Bean
for (Iterator i = Items.iterator (); I.hasnext ();) {
Purchase.additem ((Item) I.next ());
}
//Look up another bean
Object obj = ctx.lookup ("Java:comp/env/ejb/inventoryhome");
Inventoryhome inventoryhome =
(inventoryhome) portableremoteobject.narrow (obj, inventoryhome.class);
Inventory Inventory = Inventoryhome.findbystorename (storename);
//Work on the Bean
for (Iterator i = Items.iterator (); I.hasnext ();)
Inventory.markassold ((Item) I.next ());
}
//Do some the other stuff
}
Although this example is somewhat deliberate, it does reveal some of the most obvious problems with JNDI use. For starters, you should ask yourself if it is necessary to create a new InitialContext object. It's possible that this context has been loaded elsewhere in the application code, and we've created a new one here. The cache InitialContext instance immediately prompts performance improvements, as shown in Listing 2:
Listing 2. Cache InitialContext Instance
public static Context getInitialContext() {
if (initialContext == null) {
initialContext = new InitialContext();
}
return initialContext;
}
By using the helper class for Getinitialcontext () instead of instantiating a new initialcontext for each operation, we reduce the number of contexts that are spread across the application to one.
What happens to threading?
If you're worried about the line Chenghua of the solution presented here, that's not necessary. It is absolutely possible for two threads to Getinitialcontext () at the same time (thereby creating two contexts at a time), but this type of error occurs only the first time the method is called. Because the problem occurs at most once, synchronization is unnecessary, and in fact, synchronization introduces more complexity than it solves.