It’s javax naming. InitialContext ThreadSafe
At present, I am using the following code to find EJB 3 saturated session beans for normal POJO classes (we are in jee5, so we can't inject stateless session beans into ordinary POJO classes. I have to use lookup.)
import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.log4j.Logger; public Object getEJB(String jndiName) { logger.debug("WEBSPHERE EJB Lookup : " + jndiName); String modifiedJndiName = ""; Hashtable<Object,Object> properties = new Hashtable<Object,Object>(); properties.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory"); properties.put(Context.PROVIDER_URL,"iiop://localhost:2809"); try { Context context = new InitialContext(properties); logger.debug("WEBSPHERE EJB Lookup Modified JNDI Name: " + modifiedJndiName); return context.lookup("ejblocal:"+modifiedJndiName); }catch (NamingException ne) { logger.debug("Naming Exception occurred :"+jndiName +">>>"+ne.getMessage()); logger.error(ne.getMessage(),ne); } return null; }
Is the context object thredsafe? Should I create a context object for each call [as shown in this code snippet], or can I reuse the context of all threads?
Solution
The answers about thread safety are usually mentioned in Javadoc, whenever In fact, the initialcontext Javadoc mentions the following:
The last sentence confirms this: it is not thread safe, and the synchronization of each thread is necessary However, in your particular code example, no synchronization is required because it is always created locally within the method (that is, it is never shared between threads) If initialcontext is an instance variable in your specific code example, you must add the synchronized keyword to the getejb () method