This Java code snippet 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 WebSphere Application Server - Express 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 the datasource, since it should rarely change. o = ctx.lookup("java:comp/env/jdbc/MyDataSource"); // Narrow, etc. ... // Do not use cache if data is volatile. o = noCacheCtx.lookup("com/mycom/VolatileObject"); // ... } catch(javax.naming.NamingException e) { // error-handling code }