是javax.naming.InitialContext ThreadSafe

前端之家收集整理的这篇文章主要介绍了是javax.naming.InitialContext ThreadSafe前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我正在使用以下代码来查找用于正常POJO类的EJB3饱和会话bean. (我们在JEE5中,所以我们无法在普通POJO类中注入无状态会话Bean,我必须使用查找)
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;  
            }

Context对象是ThredSafe吗?我应该为每个调用创建Context对象[如该代码片段所示],或者我可以重用所有线程的Context?

解决方法

关于线程安全性的回答通常在javadoc中都有提及,无论何时.事实上,InitialContext javadoc提到如下:

An InitialContext instance is not synchronized against concurrent access by multiple threads. Multiple threads each manipulating a different InitialContext instance need not synchronize. Threads that need to access a single InitialContext instance concurrently should synchronize amongst themselves and provide the necessary locking.

最后一句话证实了这一点:它不是线程安全的,每个线程的同步是必要的.然而,在您的特定代码示例中,无需进行任何同步,因为它始终在方法局部范围内创建(即绝对不会在线程之间共享).如果InitialContext在你的特定代码示例中是一个实例变量,那么你必须将synchronized关键字添加到getEJB()方法.

猜你在找的Java相关文章