JNDI coding examples
The Java code snippet below demonstrates several techniques for controlling JNDI cache behavior, discussed in JNDI cache properties. Note that the caching discussed in this section pertains only to the WAS implementation of the initial context factory. Assume that the property, java.naming.factory.initial, is set to "com.ibm.ejs.ns.WsnInitialContextFactory" as a java.lang.System property.
import java.util.Hashtable; import javax.naming.InitialContext; import javax.naming.Context; import com.ibm.websphere.naming.PROPS; // ... class declaration, method declaration code here ... Hashtable env; Context ctx; // To clear a cache: // ...class declaration, method declaration code here... try { env = new Hashtable(); env.put(PROPS.JNDI_CACHE_OBJECT, PROPS.JNDI_CACHE_OBJECT_CLEARED); ctx = new InitialContext(env); } catch(javax.naming.NamingException e) { // error-handling code } // To set a cache's maximum cache lifetime to 60 minutes: try { env = new Hashtable(); env.put(PROPS.JNDI_CACHE_MAX_LIFE, "60"); ctx = new InitialContext(env); } catch(javax.naming.NamingException e) { // error-handling code } // To turn caching off: try { env = new Hashtable(); env.put(PROPS.JNDI_CACHE_OBJECT, PROPS.JNDI_CACHE_OBJECT_NONE); ctx = new InitialContext(env); } catch(javax.naming.NamingException e) { // error-handling code } // To use caching and no caching: try { env = new Hashtable(); env.put(PROPS.JNDI_CACHE_OBJECT, PROPS.JNDI_CACHE_OBJECT_POPULATED); ctx = new InitialContext(env); env.put(PROPS.JNDI_CACHE_OBJECT, PROPS.JNDI_CACHE_OBJECT_NONE); Context noCacheCtx = new InitialContext(env); } catch(javax.naming.NamingException e) { // error-handling code } try { Object o; // Use caching to look up home, since the home should rarely change. o = ctx.lookup("java:comp/env/ejb/MyEJBHome"); // Narrow, etc. ... // Do not use cache if data is volatile. o = noCacheCtx.lookup("com/mycom/VolatileObject"); // ... } catch(javax.naming.NamingException e) { // error-handling code }