In WebSphere Portal, Web Content Manager and WebSphere Application Server Java Naming and Directory Interface (JNDI) lookups are performed very frequently to lookup references to Distributed Cache (Dynacache), Portal Services like PUMA or NavigationService, Portlet Services, datasources, mail services, and many more. Little known is the fact that these lookups are very expensive in terms of performance. Especially in areas that are executed frequently like the theme, common portlets, SessionValidatorFilter code, or frequent database calls, the overall performance can be impacted.
To solve this issue cache the reference you have looked up and reuse it (in case it is thread-safe what most references are). For java classes a static initializer block or init method can be a good place, for Java Server Pages (jsp's) the jspInit() method is a good place.
The sample below shows an unoptimized and optimized implementation of a JNDI lookup from a jsp:
Unoptimized:
Unoptimized:
<%
javax.naming.InitialContext context = null;
try {
context = new javax.naming.InitialContext();
PortalLocalizedContextHome locCtxhome = (PortalLocalizedContextHome) context.lookup(PortalLocalizedContextHome.JNDI_NAME);
LocalizedContext localeContext = locCtxhome.getLocalizedContext(request);
// use localeContext ...
} catch (NamingException e)
{
//Exception handling
}
%>
javax.naming.InitialContext context = null;
try {
context = new javax.naming.InitialContext();
PortalLocalizedContextHome locCtxhome = (PortalLocalizedContextHome) context.lookup(PortalLocalizedContextHome.JNDI_NAME);
LocalizedContext localeContext = locCtxhome.getLocalizedContext(request);
// use localeContext ...
} catch (NamingException e)
{
//Exception handling
}
%>
Optimized:
<%!
static PortalLocalizedContextHome locCtxhome = null;
public void jspInit()
{
try {
javax.naming.InitialContext context = null;
context = new javax.naming.InitialContext();
locCtxhome = (PortalLocalizedContextHome) context.lookup(PortalLocalizedContextHome.JNDI_NAME);
} catch (NamingException e)
{
//Exception handling
}
}
%>
<%
if(locCtxhome!=null)
{
LocalizedContext localeContext = locCtxhome.getLocalizedContext(request);
//use localeContext ...
}
%>
static PortalLocalizedContextHome locCtxhome = null;
public void jspInit()
{
try {
javax.naming.InitialContext context = null;
context = new javax.naming.InitialContext();
locCtxhome = (PortalLocalizedContextHome) context.lookup(PortalLocalizedContextHome.JNDI_NAME);
} catch (NamingException e)
{
//Exception handling
}
}
%>
<%
if(locCtxhome!=null)
{
LocalizedContext localeContext = locCtxhome.getLocalizedContext(request);
//use localeContext ...
}
%>